2015-02-10 76 views
-1

我目前正在研究一个包含TreeView的WinForm。 不知何故,我无法正确填充TreeView。C#TreeView以编程方式向GrandChildren添加子节点等等

更多的知名度:

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

AnotherParentDevice... 

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

我试着给设备的索引号来识别家长和孩子。

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

我可以用上面的一种解决方案,但这些设备可以有无限的孩子​​,我不能去,如:

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

我想你们明白。

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

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

+1

使用收集集合等等和**递归**来填充这样的树。集合可以是任何东西('IList','IEnumerable',...)。 – Sinatr 2015-02-10 16:00:22

+1

你的输入数据是什么样的? – Servy 2015-02-10 16:04:19

+0

Sinatr,谢谢你的回答我会试试看。 @Servy,输入总是一个字符串。我正在使用的方法是通过注册表,并返回USB设备描述,如果该设备有任何孩子,该方法再次进入并给孩子。这就是为什么我需要一棵树。 – Megajin 2015-02-11 09:02:09

回答

0

我自己找到了解决方案。

由于我使用的是递归方法,因此不需要给父母一个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"); 

等。 该方法将跳回并使用下一个根设备作为父项。这很简单。

相关问题