Santosh Kokatnur
Santosh Kokatnur

Reputation: 364

How to Check or Uncheck All Child Nodes in TreeView

I have a Deselect button in my application, but its not working well. If I am going to deselect the folder it will deselect. But the folder within a subfolder will remain selected(checked).

Any help with this issue would be appreciated.

enter image description here

Upvotes: 1

Views: 3651

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You should find all nodes including descendants and then set Checked=false.

For example you can use this extension method to get all descendant nodes of tree or descendants of a node:

using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;

public static class Extensions
{
    public static List<TreeNode> Descendants(this TreeView tree)
    {
        var nodes = tree.Nodes.Cast<TreeNode>();
        return nodes.SelectMany(x => x.Descendants()).Concat(nodes).ToList();
    }

    public static List<TreeNode> Descendants(this TreeNode node)
    {
        var nodes = node.Nodes.Cast<TreeNode>().ToList();
        return nodes.SelectMany(x => Descendants(x)).Concat(nodes).ToList();
    }
}

Then you can use above methods on tree or a node to uncheck all descendant nodes of tree or uncheck all descendant nodes of a node:

Uncheck descendant nodes of tree:

this.treeView1.Descendants().Where(x => x.Checked).ToList()
              .ForEach(x => { x.Checked = false; });

Uncheck descendant nodes of a node:

for example for node 0:

this.treeView1.Nodes[0].Descendants().Where(x => x.Checked).ToList()
              .ForEach(x => { x.Checked = false; });

Don't forget to add using System.Linq;

Upvotes: 5

Related Questions