C#のtreeviewバインドデータベース(再帰アルゴリズム)
6452 ワード
最近面接の私に2つのテーマをあげて、1つはIQテストで、2つ目はテーマの言うことです
合計2つのテーブル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));
実装されたコード記録は以下の通りである.
合計2つのテーブル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)
{
}
}