效果图:
数据库表:
DirID:目录的ID,ParentID:目录的父路径ID,Name:目录的名字
主要代码: using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Data.SqlClient;public partial class DropdownlistTree : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e){ if (!IsPostBack){ DataTable datatable = this.GetDataTable();DataRow[] row = datatable.Select("ParentID='-1'");//添加根目录ListItem li = new ListItem(row[0]["Name"].ToString());DropDownList1.Items.Add(li);addOtherDll("", Convert.ToInt32(row[0]["DirID"]), datatable,1);}}/** <summary>/// 添加其他节点/// </summary>/// <param name="Pading">空格</param>/// <param name="DirId">父路径ID</param>/// <param name="datatable">返回的datatable</param>/// <param name="deep">树形的深度</param>private void addOtherDll(string Pading, int DirId, DataTable datatable,int deep){ DataRow[] rowlist=datatable.Select("ParentID='"+DirId+"'");foreach (DataRow row in rowlist){ string strPading = "";for (int j = 0; j < deep; j++){ strPading += " "; //用全角的空格}//添加节点ListItem li = new ListItem(strPading + "|--" + row["Name"].ToString());DropDownList1.Items.Add(li);//递归调用addOtherDll函数,在函数中把deep加1addOtherDll(strPading,Convert.ToInt32(row["DirID"]), datatable,deep+1);}}/** <summary>/// 从数据库中读取数据返回datatable/// </summary>/// <returns></returns>private DataTable GetDataTable(){ SqlConnection conn = newSqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString);SqlDataAdapter adp = new SqlDataAdapter("select * from Test", conn);DataSet datset = new DataSet();conn.Open();adp.Fill(datset, "Test");return datset.Tables[0];}}
当然,当读取DropDownList时若要去除"|--"和空格可以调用addOtherDll.SelectValue().Replace("|--","").Trim()