C# TreeView控件的应用
时间:2011-03-07 来源:我只有背影
TreeView三级节点的添加,研究了一下。不是最好的方法。如有好的方法欢迎各位一起学习一下。下面是效果图:
load事件
View Code1 private void Form3_Load(object sender, EventArgs e)
2 {
3 Bind_TreeView(treeView1, "Dname");
4 }
父节点的添加
View Code1 /// <summary>
2 /// TreeView的数据绑定父节点函数
3 /// </summary>
4 /// <param name="treeview">TreeView控件ID名称</param>
5 /// <param name="text">树控件要显示的文本的字段名称</param>
6 public void Bind_TreeView(TreeView treeview, string text)
7 {
8 DataSet DsPNode = new DataSet();
9 DsPNode = Query("select * from [test]");
10 treeview.Nodes.Clear();
11 for (int i = 0; i < DsPNode.Tables[0].Rows.Count; i++)
12 {
13 TreeNode rootnode = new TreeNode();//创建根节点
14 rootnode.Text = DsPNode.Tables[0].Rows[i][text].ToString();
15 treeview.Nodes.Add(rootnode);//在添加完节点的内容之后,当然要添加根节点,
16 CreateChildNodes(rootnode, text, "deptname", rootnode.Text);//DsPNode.Tables[0].Rows[i][text].ToString()
17 }
18 }
子节点添加
View Code1 /// <summary>
2 /// TreeView的数据绑定子节点函数
3 /// </summary>
4 /// <param name="treenode">上一级节点</param>
5 /// <param name="parentName">数据表中字段名</param>
6 /// <param name="text">树控件要显示的文本的字段名称</param>
7 /// <param name="index">查询语句关键字</param>
8 public void CreateChildNodes(TreeNode treenode, string parentName, string text, string index)
9 {
10 DataSet DsCNode = Query("SELECT deptname,node from test1 where node= '" + index + "'");
11 for (int i = 0; i < DsCNode.Tables[0].Rows.Count; i++)
12 {
13 TreeNode childnode = new TreeNode();
14 childnode.Text = DsCNode.Tables[0].Rows[i][text].ToString();
15 treenode.Nodes.Add(childnode);
16 CreateGrandsonNodes(childnode, text, "name", childnode.Text);//DsCNode.Tables[0].Rows[i][text].ToString()
17 }
18 }
三级节点的添加(方法和上一个一样,总感觉这种方法不是很好。但是又想不出别的方法)
View Code1 /// <summary>
2 /// TreeView的数据绑定三级节点函数
3 /// </summary>
4 /// <param name="treenode">上一级节点</param>
5 /// <param name="parentName">数据表中字段名</param>
6 /// <param name="text">树控件要显示的文本的字段名称</param>
7 /// <param name="index">查询语句关键字</param>
8 public void CreateGrandsonNodes(TreeNode treenode, string parentName, string text, string index)
9 {
10 DataSet ds = Query("SELECT name,deptname from test2 where deptname= '" + index + "'");
11 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
12 {
13 TreeNode childnode = new TreeNode();
14 childnode.Text = ds.Tables[0].Rows[i][text].ToString();
15 treenode.Nodes.Add(childnode);
16 }
17 }
附:
View Code1 /// <summary>
2 /// 执行查询语句,返回DataSet
3 /// </summary>
4 /// <param name="sqlstr">SQL查询语s句</param>
5 /// <returns>DataSet</returns>
6 public DataSet Query(string sqlstr)
7 {
8 using (SqlConnection conn = new SqlConnection(sql))
9 {
10 DataSet ds = new DataSet();
11 try
12 {
13 conn.Open();
14 SqlDataAdapter command = new SqlDataAdapter(sqlstr, conn);
15 command.Fill(ds, "ds");
16 }
17 catch(SqlException ex)
18 {
19 throw new Exception(ex.Message);
20 }
21 return ds;
22 }
23 }
相关阅读 更多 +