<%@ Page Language="C#" AutoEventWireup="true" %> <%@ Import Namespace="System.Data" %> <!DOCTYPE html> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { DataTable data = GetDataSource(); BindTreeView(data, tree1.Nodes, "0", "id", "pid", "name"); //绑定树控件 } public void BindTreeView(DataTable dt, TreeNodeCollection tnc, string pid_val, string id_Name, string pid_Name, string text_Name) { DataView dv = new DataView(dt);//将DataTable存到DataView中,以便于筛选数据 TreeNode tn;//建立TreeView的节点(TreeNode),以便将取出的数据添加到节点中 //以下为三元运算符,如果父id为空,则为构建“父id字段 is null”的查询条件,否则构建“父id字段=父id字段值”的查询条件 string filter = string.IsNullOrEmpty(pid_val) ? pid_Name + " is null" : string.Format(pid_Name + "=‘{0}‘", pid_val); dv.RowFilter = filter;//利用DataView将数据进行筛选,选出相同 父id值 的数据 foreach (DataRowView drv in dv) { tn = new TreeNode();//建立一个新节点 tn.Value = drv[id_Name].ToString();//节点的Value值,一般为数据库的id值 tn.Text = drv[text_Name].ToString();//节点的Text,节点的文本显示 tnc.Add(tn);//将该节点加入到TreeNodeCollection(节点集合)中 BindTreeView(dt, tn.ChildNodes, tn.Value, id_Name, pid_Name, text_Name);//递归(反复调用这个方法,直到把数据取完为止) } } private DataTable GetDataSource() { /*ID是列主键,PID是字段,name是字段名*/ DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("id", typeof(int)));//id列 类型guid dt.Columns.Add(new DataColumn("pid", typeof(int)));//父id列 类型guid dt.Columns.Add(new DataColumn("name", typeof(string)));//名称列 类型string dr = dt.NewRow(); dr["id"] = "1"; dr["pid"] = "0"; dr["name"] = "启明星工作室"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["id"] = 2; dr["pid"] = "1"; dr["name"] = "人事部"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["id"] = 3; dr["pid"] = "1"; dr["name"] = "财务"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["id"] = 4; dr["pid"] = "2"; dr["name"] = "财务"; dt.Rows.Add(dr); return dt; } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TreeView runat="server" ID="tree1" ShowLines="true" ImageSet="Arrows"> </asp:TreeView> </div> </form> </body> </html>