且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何选中或取消选中 TreeView 中的所有子节点

更新时间:2023-10-19 18:17:40

你应该找到所有节点,包括后代,然后设置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:

取消选中树的后代节点:

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

取消选中节点的后代节点:

例如节点 0:

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

不要忘记添加using System.Linq;