如何将TreeView节点动态添加为已创建节点的子节点

时间:2018-10-04 10:03:12

标签: asp.net treeview nodes

在我的asp.net mvc 5项目中,我有一个TreeView,它从数据库(PostgreSQL)中获取数据。这是我在页面中看到的样子: enter image description here     enter image description here 问题是如何将它们放在“执行器”节点下?如何将它们添加为“执行器”节点的子级     这是代码:

   <asp:TreeView ID="TreeView1" runat="server">
                        <Nodes>
                            <asp:TreeNode Text="Executor" Value="Executor">
                                <asp:TreeNode Text="ShowAll" Value="showAll"></asp:TreeNode>
                            </asp:TreeNode>
                        </Nodes>
                        </asp:TreeView>

以及后面的代码:

 private void GetTreeViewItems()
    {
        string connStr = ConfigurationManager.ConnectionStrings["PGcon"].ConnectionString;
        NpgsqlConnection con = new NpgsqlConnection(connStr);
        NpgsqlDataAdapter da = new NpgsqlDataAdapter("SELECT username FROM users", conCon); 
        DataSet ds = new DataSet();
        daDa.Fill(ds);      
        foreach (DataRow level1DataRow in ds.Tables[0].Rows)
        {
            TreeNode parentTreeNode = new TreeNode();
            parentTreeNode.Text = level1DataRow["username"].ToString();          
            TreeView1.Nodes.Add(parentTreeNode);

        }

1 个答案:

答案 0 :(得分:0)

我解决了这个问题!

TreeNode a1 = new TreeNode("Apple");
        TreeView1.Nodes.Add(a1);
        foreach (DataRow level1DataRow in dsDs.Tables[0].Rows)
        {
            TreeNode parentTreeNode = new TreeNode();
            parentTreeNode.Text = level1DataRow["username"].ToString();
            //TreeView1.Nodes.Add(parentTreeNode);


            a1.ChildNodes.Add(parentTreeNode);

        }