获取所有检查节点及其子节点树状列表 [英] Get list of all checked nodes and its subnodes in treeview
问题描述
我有一个树状列表复选框,列表中包含的节点,子节点和子节点中的某些情况下,子节点。当用户检查一些项目,我想获得所选项目的列表
I have a treeview list check boxes and the list contains nodes, subnodes and in some cases subnode of subnode. When user check some items i want to get list of selected items.
在此,为什么我只得到selcted主节点的项目:
On this why I get only selcted items of main node:
foreach (System.Windows.Forms.TreeNode aNode in tvSastavnica.Nodes)
{
if (aNode.Checked == true)
{
Console.WriteLine(aNode.Text);
}
}
如何通过整个树状特拉弗斯并得到检查的项目?子节点
How to travers through whole treeview and get checked items in subnodes?
推荐答案
如果您喜欢LINQ,你可以创建一个横贯整个树视图扩展方法:
If you like LINQ, you can create an extension method that traverses the whole treeview:
internal static IEnumerable<TreeNode> Descendants(this TreeNodeCollection c)
{
foreach (var node in c.OfType<TreeNode>())
{
yield return node;
foreach (var child in node.Nodes.Descendants())
{
yield return child;
}
}
}
然后就可以执行所有的操作您想使用LINQ。在你的情况,让选择的节点列表很简单:
Then you can perform every operations you want using LINQ. In your case, getting a list of selected nodes is easy:
var selectedNodes = myTreeView.Nodes.Descendants()
.Where(n => n.Checked)
.Select(n => n.Text)
.ToList();
这种方法的一个优点是它是通用的。
An advantage of this approach is it is generic.
不过,由于后代()方法遍历整个树,它可能是一个有点比@mybirthname给出,因为它只关心那些与父母检查节点的答案效率较低。 。如果您的使用情况,包括这个约束我不知
However, because the Descendant() method traverses the whole tree, it might be a bit less efficient than the answer given by @mybirthname because it only cares about nodes that are checked with their parents. I dont known if your use case includes this constraint.
编辑:现在@mybirthname答案已被编辑,它这样做。现在你有循环和LINQ的解决方案,无论是递归的。
Now @mybirthname answer has been edited, it is doing the same. Now you have the loop and the LINQ solution, both are recursive.
这篇关于获取所有检查节点及其子节点树状列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!