How to Check or Uncheck All Child Nodes in TreeView

白昼怎懂夜的黑 提交于 2020-01-30 02:41:16

问题


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.


回答1:


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;



来源:https://stackoverflow.com/questions/34921308/how-to-check-or-uncheck-all-child-nodes-in-treeview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!