Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

c# - 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
        }
    }
}

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.

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.

EDIT: Now @mybirthname answer has been edited, it is doing the same. Now you have the loop and the LINQ solution, both are recursive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...