且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有动态子项的窗口形式树视图

更新时间:2023-10-19 18:14:04

我为您创建了一个示例,您可以在其中了解如何在您的示例中进行操作.

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