Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winform TreeView with checkboxes - only visible nodes are updated

I am new here, and have searched for answers for my problem practically everywhere - to no avail. I hope that somebody here can help.

I have a WinForm application, where I use a TreeView to display the folder structure below a selected root folder. The treeview has enabled CheckBoxes. When I check or uncheck a checkbox on a TreeNode, any visible nodes below that TreeNode changes as well - so far so good.

The problem is, that when I expand the nodes further, then the new visible nodes are not updated to the correct state.

I used the following recursive routine to perform the update:

    private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
    {
        foreach (TreeNode node in treeNode.Nodes)
        {
            node.Checked = nodeChecked;
            if (node.Nodes.Count > 0)
            {
                // If the current node has child nodes, call the
                // CheckAllChildNodes method recursively.
                CheckAllChildNodes(node, nodeChecked);
            }
        }
    }

It is called from this event handler:

    private void FileTreeView_AfterCheck(object sender, TreeViewCancelEventArgs e)
    {
        // The code only executes if the user caused the checked state to change.
        if (e.Action == TreeViewAction.ByMouse)
        {
            if (e.Node.Nodes.Count > 0)
            {
                // Calls the CheckAllChildNodes method, passing in the current
                // checked value of the TreeNode whose checked state changed.
                CheckAllChildNodes(e.Node, e.Node.Checked);
            }
        }
    }

It seems that the recursive function only cares about TreeNodes that are visible at the time of execution.

If anyone can give a clue of what is wrong, and what can be done to correct it, it will be greatly appreciated.

Thanks in advance.

Best regards,

L. Hummel

like image 724
L. H. Avatar asked Nov 26 '25 14:11

L. H.


1 Answers

Two things. One, you don't need the "if (e.Node.Nodes.Count > 0)" in either. That is a little redundant as if there are 0 nodes when you call a "foreach", it immediately passes out of the loop.

Two, the easiest solution may be to just wire into the AfterExpand method, and when the node gets expanded, set the children then:

private void FileTreeView_AfterExpandobject sender, TreeViewEventArgs e)
{
    // Calls the CheckAllChildNodes method, passing in the current
    // checked value of the TreeNode whose checked state changed.
    CheckAllChildNodes(e.Node, e.Node.Checked);        
}

Also, are you sure you want TreeViewCancelEventArgs in your event methods, and not just TreeViewEventArgs?

like image 191
krillgar Avatar answered Nov 29 '25 02:11

krillgar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!