我无法弄清楚如何将子节点添加到树视图

时间:2014-03-12 14:43:09

标签: c# winforms treeview

这是我的代码:

public Form1()
{
    InitializeComponent();
    treeView1.Nodes.Add(new TreeNode("Graphic Requests"));
    if (TreeNodesList == null) TreeNodesList = new List<TreeNode>();
    TreeNodesList.Add(new TreeNode("Art Not Started"));
    TreeNodesList.Add(new TreeNode("Art In Progress"));
    TreeNodesList.Add(new TreeNode("Items To Accept/Modify"));
    TreeNodesList.Add(new TreeNode("Final Art Not Locked"));

    foreach (var node in TreeNodesList)
    {
        treeView1.Nodes.Add(node);
    }
}

我原本希望有一个父节点“图形请求”,其余节点作为子节点添加。但是,我的列表看起来像这样:

Resulting list

有人可以告诉我我错过了什么吗?

5 个答案:

答案 0 :(得分:2)

您将节点添加到treeView1,这就是为什么它们是父节点而不是子节点的原因。而是将它们添加到您添加的第一个节点。

试试这个:

public Form1()
{
   InitializeComponent();
   var parent = new TreeNode("Graphic Requests");

   TreeNodesList.Add(new TreeNode("Art Not Started"));
   TreeNodesList.Add(new TreeNode("Art In Progress"));
   TreeNodesList.Add(new TreeNode("Items To Accept/Modify"));
   TreeNodesList.Add(new TreeNode("Final Art Not Locked"));

   foreach (var node in TreeNodesList)
   {
       parent.Nodes.Add(node);
   }
   treeView1.Nodes.Add(parent);
}

答案 1 :(得分:1)

您需要将子节点添加到父节点的节点集合中,否则它们不是子节点,而是父节点的兄弟节点。

public Form1()
{
    InitializeComponent();

    var parentNode = new TreeNode("Graphic Requests");

    if (TreeNodesList == null) TreeNodesList = new List<TreeNode>();
    TreeNodesList.Add(new TreeNode("Art Not Started"));
    TreeNodesList.Add(new TreeNode("Art In Progress"));
    TreeNodesList.Add(new TreeNode("Items To Accept/Modify"));
    TreeNodesList.Add(new TreeNode("Final Art Not Locked"));

    foreach (var node in TreeNodesList)
    {
        parentNode.Nodes.Add(node);
    }
    treeView1.Nodes.Add(parentNode);
}

答案 2 :(得分:1)

首先需要将根节点添加到树中,然后才能添加子节点:

treeView1.Nodes.Add(new TreeNode("Graphic Requests")); // ROOT NODE

TreeNode parentNode = treeView2.Nodes[0];
if (parentNode != null)
{
  parentNode.Add(new TreeNode("Art Not Started"));
  parentNode.Add(new TreeNode("Art In Progress"));
  parentNode.Add(new TreeNode("Items To Accept/Modify"));
  parentNode.Add(new TreeNode("Final Art Not Locked"));
}

答案 3 :(得分:1)

您实际上是将所有节点直接添加到树视图中。应将子节点添加到作为父节点的“Graphic”,然后将父节点添加到树视图中。 试试这个:

public Form1()
{
    InitializeComponent();
    TreeNode parent = new TreeNode("Graphic Requests")
    if (TreeNodesList == null) TreeNodesList = new List<TreeNode>();
    TreeNodesList.Add(new TreeNode("Art Not Started"));
    TreeNodesList.Add(new TreeNode("Art In Progress"));
    TreeNodesList.Add(new TreeNode("Items To Accept/Modify"));
    TreeNodesList.Add(new TreeNode("Final Art Not Locked"));

    foreach (var node in TreeNodesList)
    {
        parent.Nodes.Add(node);
    }
    treeView1.Nodes.Add(parent);
}

答案 4 :(得分:0)

您必须执行以下操作才能附加到父级:

foreach (var node in TreeNodesList)
{
    treeView1.Nodes[0].Nodes.Add(node);
}

如果您想了解有关填写TreeView的更多信息,建议您使用以下article