问题
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