C# 中的treeview绑定数据库(递归算法)
近日面试的给我两道题目,一道是IQ测试,第二个就是题目所言
总共两个表 department(id int not null primary key,parentid int,name char(50));
employee(id int not null foreign key(id) references department(id) ,departmentid,name char(50));
实现的代码记录如下
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class Default01 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { fill_Tree(); } void fill_Tree() { SqlConnection SqlCon = new SqlConnection("server=(local);uid=sa;pwd=sa;database=test"); SqlCon.Open(); SqlCommand SqlCmd = new SqlCommand("Select id,name from department", SqlCon); SqlDataReader Sdr = SqlCmd.ExecuteReader(); SqlCmd.Dispose(); string[,] ParentNode = new string[10000, 2]; int count = 0; while (Sdr.Read()) { ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("id")).ToString(); ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("name")).ToString(); } Sdr.Close(); for (int loop = 0; loop < count; loop++) { TreeNode root = new TreeNode(); root.Text = ParentNode[loop, 1]; root.Target = "_blank"; root.NavigateUrl = "Default01.aspx"; SqlCommand Module_SqlCmd = new SqlCommand("Select name,id from employee where departmentid =" + ParentNode[loop, 0], SqlCon); SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader(); while (Module_Sdr.Read()) { TreeNode child = new TreeNode(); child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("name")).ToString(); child.Target = "_blank"; child.NavigateUrl = "Default01.aspx"; root.ChildNodes.Add(child); } Module_Sdr.Close(); TreeView1.Nodes.Add(root); } TreeView1.CollapseAll(); SqlCon.Close(); } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { } }