C#递归所以部门展示到TreeView

来源:互联网 发布:winform三层架构源码 编辑:程序博客网 时间:2024/04/30 01:13

C#递归所以部门展示到TreeView

1.首先是数据库表的设计

  新建一张部门表:TestUser表

  1.ID自增int主键 2.DeptName:nchar(10)3.DeptCode:nchar(10)4:ParentID:nchar(10)

2.部门表就建好了

3.新建一个网站

4.在网站的default.aspx界面拖一个TreeView控件。

5.aspx.cs代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public static string strConn=ConfigurationManager.ConnectionStrings["connString"].ConnectionString.ToString();//数据库连接串
 
protected void Page_Load(object sender,EventArgs e)
{
   if(!isPostBack)
{
    BindDeptTree("0");//数据库你也可以设计成int类型
}
}
 
private void BindDeptNode(TreeNode DTnode)
{
   try
{
 DataSet=reDs("select DeptName,DeptCode from TestUser where ParentID='"+DTnode.Value+"'");
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
   TreeNode node=new TreeNode();
   node.Text=ds.Tables[0].Rows[i]["DeptName"].ToString();
   node.Value=ds.Tables[0].Rows[i][DeptCode].ToString();
   DTnode.ChildNodes.Add(node);//把指定的节点添加到控件中
   BindDeptNode(node);
}
}
catch(Exception ex)
{
   Log.LogWrite(ex.Message);
}
}
 
 
private void BindDeptTree(string ParentID)
{
DataSet=reDs("select DeptName,DeptCode from TestUser where ParentID='"+DTnode.Value+"'");
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
   TreeNode node=new TreeNode();
   node.Text=ds.Tables[0].Rows[i]["DeptName"].ToString();
   node.Value=ds.Tables[0].Rows[i][DeptCode].ToString();
   tvData.Nodes.Add(node);//TreeView的IDtvData
   BindDeptNode(node);
}
}
 
 
public DataSet reDs(string strSql)
{
  using(SqlConnection conn=new Sqlconnection(strConn))
{
   conn.Open();
   DataSet ds=new DataSet();
   SqlDataAdapter da=new SqlDataAdapter (strSql,conn);
   da.Fill(ds);
   conn.close();
   return ds;
}
}

运行结果如下图:

希望对大家有帮助。有不足的地方望指教。尊重原创,转载请注明出处。

0 0
原创粉丝点击