C# TreeView 使用 GrandChildren 等以编程方式添加 Child 个节点

C# TreeView Programmatically Adding Child Nodes With GrandChildren And So On

我目前正在开发一个包含 TreeView 的 WinForm。 不知何故,我无法正确填充 TreeView。

为了提高知名度:

Parent Device -
              |-ChildDevice1-
              |             |-GrandChild1 (not connected with ChildDevice2)
              |-ChildDevice2

AnotherParentDevice...

and so on...
(this is how it should look like)

我试图给设备一个 index-number 来识别 parent 和 child。

treeView1.Nodes.Add(new TreeNode("Parent"));
treeView1.Nodes[parentid].Nodes.Add(new TreeNode("Child"));
treeView1.Nodes[parentid].Nodes[childid].Nodes.Add(new TreeNode("GrandChild"));

我可以使用上面的解决方案,但是设备可以有无限的 children 而我不能这样:

treeView1.Nodes[parentid].Nodes[childid].Nodes[GrandChild1].Nodes[GrandChild2].Nodes.Add(new TreeNode("GrandChild2"));

我猜你们明白了。

编辑: 我正在使用的方法是通过注册表,并返回 USB 设备描述,如果设备有任何 child,该方法将再次进入并返回 child(依此类推).这就是为什么我需要一棵树

PS.: 对不起我的英语不好

我自己找到了解决办法。

因为我使用的是递归方法,所以没有必要给 parents 一个 id。因为他们已经有了。

我的代码如下所示:

    //Generate variables for the recursive Method
    TreeView tree = treeView1;
    TreeNode treeNode;

    //You set the current Node to be the Parent
    treeNode = tree.Nodes.Add("rootDevice");

    //Now if the root device has a child
    treeNode = tree.Nodes.Add("childDevice");

    // If the child has a child
    treeNode = tree.Nodes.Add("grandChildDevice");

等等。 该方法将跳回并使用下一个根设备作为 Parent。就这么简单。