数据库动态添加treeview的节点

  
    
1 数据表:deptTree
2
3 deptId int
4
5
6 deptName nvchar
7
8
9 parentId int
10
11
12 nodeValue nvchar
13
14 代码部分:
15
16
17 private DataView dvDept = null ;
18
19 private DataView dvMember = null ;
20 protected void Page_Load( object sender, EventArgs e)
21 {
22 CreateTable();
23 AddTree( - 1 , (TreeNode) null );
24 }
25
26 private void CreateTable()
27 {
28
29 try
30 {
31 OleDbConnection con = DataBase.Con;
32 OleDbCommand cmd = new OleDbCommand();
33 cmd.Connection = con;
34 // cmd.CommandText = "select department.departmentId,department.departmentName,managerId,department.higherDepartmentId,member.memberId,member.name from department,member where department.departmentId=member.departmentId ";
35   cmd.CommandText = " select * from deptTree " ;
36 OleDbDataAdapter da = new OleDbDataAdapter();
37 da.SelectCommand = cmd;
38 DataSet ds = new DataSet();
39 da.Fill(ds, " deptTree " );
40 dvDept = ds.Tables[ " deptTree " ].DefaultView;
41 con.Close();
42
43 OleDbConnection co = DataBase.Con;
44 OleDbCommand cm = new OleDbCommand();
45 cm.Connection = co;
46 // cmd.CommandText = "select department.departmentId,department.departmentName,managerId,department.higherDepartmentId,member.memberId,member.name from department,member where department.departmentId=member.departmentId ";
47 cm.CommandText = " select departmentId,memberId,name from member order by departmentId " ;
48 OleDbDataAdapter daa = new OleDbDataAdapter();
49 daa.SelectCommand = cm;
50 DataSet dss = new DataSet();
51 daa.Fill(dss, " dvMember " );
52 dvMember = dss.Tables[ " dvMember " ].DefaultView;
53 co.Close();
54
55
56
57 }
58 catch (Exception ex)
59 {
60 Response.Write( " 数据库错误,错误原因: " + ex.Message);
61 Response.End();
62 }
63 }
64
65 public void AddTree( int parentId, TreeNode pNode)
66 {
67 dvDept.RowFilter = " parentId= " + parentId;
68 foreach (DataRowView row in dvDept)
69 {
70 TreeNode Node = new TreeNode();
71 if (pNode == null ) // 当节点的父节点为空,则添加当前节点为根节点
72 {
73 Node.Text = row[ " deptName " ].ToString() ;
74 Node.Value = row[ " nodeValue " ].ToString();
75 TreeView1.Nodes.Add(Node);
76 Node.Expanded = true ;
77 AddTree(Int32.Parse(row[ " deptId " ].ToString()), Node); // 再次递归
78 }
79 else
80 {
81 // 添加当前节点的子节点
82 Node.Text = " <a href='#' onDblClick=\ " abc( ' " + row["nodeValue"].ToString() + " ' , ' " + row["deptName"].ToString() + " ' )\ " > " + row[ " deptName " ].ToString() + " </a> " ;
83 Node.Value = row[ " nodeValue " ].ToString();
84 pNode.ChildNodes.Add(Node);
85 Node.Expanded = true ; // 节点状态展开
86 AddTree(Int32.Parse(row[ " deptId " ].ToString()), Node); // 再次递归
87 }
88 }
89
90 }
91
92
93
94

 

你可能感兴趣的:(treeview)