将子节点添加到树视图

将子节点添加到树视图

问题描述:

你好,

我有一个树状视图.与此相似;


-儿童1
-孩子1的孩子a
-孩子1的孩子b

我正在从文本框中添加子项a和子项b,但它只是继续在子项1下添加值.相反,我想将它们添加到新节点上.我该怎么办?

喜欢;

Hello,

I have a treeview. It is similar to this;

Root
-Child 1
-Child a of Child 1
-Child b of Child 1

I am adding the child a and child b from textboxes but it just keeps adding the values under of the child 1. Instead I want to add them on a new node. How can I do this?

Like;

Root
    -Child 1
       -Child a of Child 1
       -Child b of Child 1
    -Child 2
       -Child a of Child 2
       -Child b of Child 2
    -Child 3
       -Child a of Child 3
       -Child b of Child 3

我可以在另一个例子中添加一些KISS(保持简单和愚蠢):

如果您已经拥有treeView或刚刚创建了它的实例:
让我们填充一些数据-例如一位父母两个孩子:
May i add another example some KISS (Keep It Simple & Stupid):

If you already have a treeView or just created an instance of it:
Let''s populate with some data - Ex. One parent two child''s :
treeView1.Nodes.Add("ParentKey","Parent Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");



另一个例子两个父母的第一个孩子有两个孩子,第二个一个孩子:



Another Ex. two parent''s first have two child''s second one child:

treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");


如果走得更远-孩子2的子孩子:


Take if farther - sub child of child 2:

treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");



如您所见,您可以根据需要拥有任意数量的子代和父代,而这些子代可以有子代的子代,依此类推....
希望我能帮忙!



As you see you can have as many child''s and parent''s as you want and those can have sub child''s of child''s and so on....
Hope i help!


您最有可能做的是未指定要将子代添加到的节点.这是我为您制作的一个简短示例.

What you are most likely doing is not specifing the node you want to add the children to. Here is a quick little example I made for you.

TreeNode thisNode;

thisNode = treeView1.Nodes.Add("First Parent");
thisNode.Nodes.AddRange(new TreeNode[]
{
    new TreeNode("Test"),
    new TreeNode("Test #2"),
    new TreeNode("Test #3")
});

thisNode = treeView1.Nodes.Add("Second Parent");
thisNode.Nodes.AddRange(new TreeNode[]
{
    new TreeNode("Test"),
    new TreeNode("Test #2"),
    new TreeNode("Test #3")
});



第一条语句只是声明了一个变量.
第二个对象为该变量分配一个新的 TreeNode 对象.
第三个将一堆 TreeNode 对象添加到该变量,这些对象将是它的子级.



The first statement simply declares a variable.
The second assigns a new TreeNode object to that variable.
The third adds a bunch of TreeNode objects to the variable, these would be its children.