带有动态子项的窗口形式树视图 [英] windows form treeview with dynamic child
问题描述
我正在 C# 中处理 Windows 窗体,以使用数据库中的数据构建树视图.有一个存储过程,它给出了以下信息的列表
I am working on a windows form in C# to build a treeview using data from a database. There is a store procedure which give the list of following info
id - 节点 IDdescription - 要在树视图中显示的值isEndNode - 0 如果它是结束节点;1 如果此节点有子节点
id - node id description - value to be displayed in on the treeview isEndNode - 0 if it is the end node; 1 if this node has child
如果 isEndNode 是 1 那么我必须使用当前节点的 id 调用相同的存储过程来接收它下面的子节点列表.
if isEndNode is 1 then I have to call the same store procedure with id of the current node to receive a list of child node under it.
我已经构建了一个机制来调用存储过程并获取项目列表,但我不确定如何填充树结构.我在想我将第一个列表显示为父节点,当用户单击 + 符号展开时,我将调用存储过程并将新项目作为子节点添加到当前节点.我不确定如何告诉节点它是父节点而不是结束节点.有没有人建造过这样的东西?请帮忙
I have built a mechanism that will call the store procedure and get the list of items but I am not sure how to populate the tree structure. I was thinking I will show the first list as parent nodes and when the user click on + sign to expand I will call the store procedure and add the new item as child to current node. I am not sure how to tell a node that it is a parent node and not the end node. Has any one built something like this? please help
推荐答案
我为您创建了一个示例,您可以在其中了解如何在您的示例中进行操作.
I've created a sample for you, within which you can understand how to do it in yours.
在数据库中创建一个表Employees
Created a table Employees in a database
最初员工的姓名将放在TreeView上
Initially the names of the employees will be put on to the TreeView
展开姓名后,可以查看他们的年龄和电话号码.
When the name is expanded, their Age and PhoneNumber can be viewed.
public Form1()
{
InitializeComponent();
initTreeView(); //TreeView without any nodes in it
}
void initTreeView()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = _ConnectionString;
con.Open();
using (SqlCommand comm = new SqlCommand("Select Name From Employees", con))
using (SqlDataReader read = comm.ExecuteReader())
while (read.Read())
{
TreeNode tn = new TreeNode(read["Name"].ToString());
tn.Nodes.Add(new TreeNode());
treeView1.Nodes.Add(tn);
}
treeView1.BeforeExpand += treeView1_BeforeExpand;
}
void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
TreeNode tNode = e.Node;
string empName = tNode.Text;
tNode.Nodes.Clear();
SqlConnection con = new SqlConnection();
con.ConnectionString = _ConnectionString;
con.Open();
using (SqlCommand comm = new SqlCommand("Select Age, PhoneNumber From Employees Where Name = @empName", con))
{
comm.Parameters.AddWithValue("@empName", empName);
using (SqlDataReader read = comm.ExecuteReader())
if (read.Read())
{
TreeNode nodeAge = new TreeNode(read["Age"].ToString());
TreeNode nodePhone = new TreeNode(read["PhoneNumber"].ToString());
tNode.Nodes.AddRange(new TreeNode[] { nodeAge, nodePhone });
}
}
}
这篇关于带有动态子项的窗口形式树视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!