Search code examples
c#winformseventstreeviewnodes

Can you create a checked event trigger specific to a single node in a Tree View?


How can you iterate through a "tree view" such that when a parent node is checked, all child nodes are automatically checked. And then the user should be to uncheck each child node as they wish. If they uncheck all child nodes, the parent node should automatically be unchecked.

The problem with the code below is that there is way to differentiate whether a parent node or a child node triggered the event. The code can only look at the state of the tree view as it is at time of event trigger. So using this, a child node can no longer be unchecked. The only way I can think to do this is to save the previous state of the tree view to compare them to see which node, parent or otherwise was checked and go from there. I hope there is an easier method.

Thanks for the help!

private void CorridorList_AfterCheck(object sender, TreeViewEventArgs e)
    {
        this.CorridorList.AfterCheck -= CorridorList_AfterCheck;
        foreach (TreeNode node in this.CorridorList.Nodes)
        {
            // checks all child nodes if parent node is checked. 
            TreeNodeCollection ChildnodeCol =  node.Nodes;
            {
                if (node.Checked && (!ChildnodeCol[0].Checked && !ChildnodeCol[1].Checked) )
                {  
                    ChildnodeCol[0].Checked = true;
                    ChildnodeCol[1].Checked = true;
                    node.Expand();
                }
            }
        }
        this.CorridorList.AfterCheck += CorridorList_AfterCheck;
    }

Tree View Example


Solution

  • You can use e.Action to check why it was triggered. But bailing out there means you cannot use the event itself to recurse. You need to make a separate function to recurse.

    private void CorridorList_AfterCheck(object sender, TreeViewEventArgs e)
    {
        if (e.Action == TreeViewAction.Unknown)    // was triggered by code
            return;
    
        CheckSubNodes(e.Node);
    }
    
    void CheckSubNodes(TreeNode node)
    {
        foreach (TreeNode node in node.Nodes)
        {
            if (!node.Checked)
            {
                node.Checked = true;
                node.Expand();  // do you need to expand also??
                // checks all child nodes if parent node is checked. 
                CheckSubNodes(node);
            }
        }
    }