使用foreach在TreeView中创建子节点 [英] Creating child node in TreeView using foreach
本文介绍了使用foreach在TreeView中创建子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须列出< string>,其中包含以下内容(比方说):
I have to List<string>, with the following contents (let's say):
List<string> listA = new List<string>();
List<string> listB = new List<string>();
listA.Add("main1");
listA.Add("main2");
listA.Add("main3");
listB.Add("sub1");
listB.Add("sub2");
listB.Add("sub3");
现在。这就是我卡住的地方:
我想拥有以下TreeView:
Now. Here comes where I stuck:
I would like to have the following TreeView:
|
|-main1-|
| |-sub1
| |-sub2
| |-sub3
|
|-main2-|
| |-sub1
| |-sub2
| |-sub3
|
|-main3-|
| |-sub1
| |-sub2
| |-sub3
我想为每个列表使用foreach循环。以下代码给出了错误:
I wanna use foreach loop for each Lists. The following code gives me error:
foreach (string mains in listA)
{
TreeNode node = new TreeNode(mains);
foreach (string subs in listB)
{
TreeNode node2 = new TreeNode(subs);
treeView.Nodes[mains].Nodes.Add(node2);
}
treeView.Nodes.Add(node);
}
错误发生在内部foreach,但不知道为什么......树形层次结构正在制作中喜欢。请帮我纠正这个循环。
谢谢
The error is in the inner foreach, but dunno why... The tree hierarchy is being made as I like. Please help me correcting this loop.
Thanks
推荐答案
你可以简化这个:
private void makeTree(List<string> headings, List<string> items)
{
foreach (var s0 in headings)
{
TreeNode newNode = new TreeNode(s0);
treeView1.Nodes.Add(newNode);
foreach (var s1 in items)
{
newNode.Nodes.Add(new TreeNode(s1));
}
}
}
您可以这样称呼它:
makeTree(
new List<string> {"one", "two", "three"},
new List<string> {"sub1", "sub2"});
好吧,我终于明白了...错误的订购,不需要两个TreeNode。所以正确的是:
ok, I got it finally... Wrong ordering and do not need two TreeNode. So the correct is:
foreach (string mains in listA)
{
TreeNode node = new TreeNode(mains);
treeView1.Nodes.Add(node);
foreach (string subs in listB)
{
node.Nodes.Add(subs);
}
}
这篇关于使用foreach在TreeView中创建子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文