Get a list of all checked nodes and its trays in treeview

I have checkboxes in a tree view and the list contains nodes, trays and in some cases a subnode of a subnode. When the user checks some items, I want to get a list of the selected items.

For this reason, I only get selcted elements of the main node:

 foreach (System.Windows.Forms.TreeNode aNode in tvSastavnica.Nodes)
        {
            if (aNode.Checked == true)
            {
                Console.WriteLine(aNode.Text);
            }
        }

      

How do I navigate the entire tree structure and get checked items in the trays?

+3


source to share


3 answers


If you like LINQ, you can create an extension method that traverses the entire tree:

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 do whatever 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();

      



The advantage of this approach is that it is generic.

However, since the Descendant () method traverses the entire tree, it might be slightly less efficient than the answer given by @mybirthname, because it only cares about nodes that are checked along with their parents. I don't know if your use case includes this limitation.

EDIT: Now @ mybirthname's answer has been edited, it does the same thing. You now have a loop and a LINQ solution, both recursive.

+8


source


public void GetCheckedNodes(TreeNodeCollection nodes)
{
    foreach(System.Windows.Forms.TreeNode aNode in nodes)
    {
         //edit
         if(aNode.Checked)
             Console.WriteLine(aNode.Text);

         if(aNode.Nodes.Count != 0)
             GetCheckedNodes(aNode.Nodes);
    }
} 

      

You don't look into child notes using recursion, you can do it.



You need a method like this! In your code, just call once GetCheckedNodes(tvSastavnica.Nodes)

and all checked nodes should be displayed!

+3


source


my way:

void LookupChecks(TreeNodeCollection nodes, List<TreeNode> list)
{
    foreach (TreeNode node in nodes)
    {
        if (node.Checked)
            list.Add(node);

        LookupChecks(node.Nodes, list);
    }
}

      

Using:

var list = new List<TreeNode>();
LookupChecks(TreeView.Nodes, list);

      

+1


source







All Articles