Search code examples
c#winformstreeviewtabcontrol

check and uncheck all the nodes of the tree view in c#


I have the tree view in my windows application and in the tree view with the checkboxes and I have the Some "parent nodes" and some "child nodes" and i want to CHECK AND UNCHECK the parent and child nodes at a time on clicking the "Check All" and "Uncheck All" button... How should i do this?


Solution

  • Try something like this:

    public void CheckAllNodes(TreeNodeCollection nodes)
    {
        foreach (TreeNode node in nodes)
        {
            node.Checked = true;
            CheckChildren(node, true);
        }
    }
    
    public void UncheckAllNodes(TreeNodeCollection nodes)
    {
        foreach (TreeNode node in nodes)
        {
            node.Checked = false;
            CheckChildren(node, false);
        }
    }
    
    private void CheckChildren(TreeNode rootNode, bool isChecked)
    {
        foreach (TreeNode node in rootNode.Nodes)
        {
            CheckChildren(node, isChecked);
            node.Checked = isChecked;
        }
    }
    

    Edit: Check branches to tick/untick all child nodes:

    private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
    {
        CheckChildren(e.Node, e.Node.Checked);
    }