windows form treeview with dynamic child

为君一笑 提交于 2020-01-14 03:05:27

问题


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 - 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

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


回答1:


I've created a sample for you, within which you can understand how to do it in yours.

Created a table Employees in a database

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 });
            }
    }
}


来源:https://stackoverflow.com/questions/29108368/windows-form-treeview-with-dynamic-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!