1

Consider a TreeView structure such as the following:

enter image description here

The goal is to have a node's descendants check or uncheck themselves accordingly when a particular node is checked. For example, in the above, if "D" is unchecked, "D A", "D A A" and "D A B" should uncheck themselves.

Currently, the code being used is as follows:

private void treeView_AfterCheck(object sender, TreeViewEventArgs e)
{
    if (e.Action != TreeViewAction.Unknown)
    {
        if (e.Node.Checked)
        {
            checkChildNodes(e.Node.Nodes);
        }
        else
        {
            uncheckChildNodes(e.Node.Nodes);
        }
    }
 }

private void checkChildNodes(TreeNodeCollection nodes)
{
    foreach (TreeNode node in nodes)
    {
        node.Checked = true;

        if (node.Nodes.Count>0)
            checkChildNodes(node.Nodes);
    }
}

private void uncheckChildNodes(TreeNodeCollection nodes)
{
    foreach (TreeNode node in nodes)
    {
        node.Checked = false;

        if (node.Nodes.Count>0)
            uncheckChildNodes(node.Nodes);
    }
}

The problem with this is that sometimes the checking/unchecking of descendants does not occur, when the "root" node is clicked very fast. How can this be solved?

What has also been tried, is using the BeforeCheck event, as per the following link: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.treeview.aftercheck?view=netcore-3.1

Al2110
  • 566
  • 9
  • 25
  • Could it be that `treeView_AfterCheck` is called when `node.Checked = ...;` is changed inside your `uncheckChildNodes` method? If so, then add a `bool isAdjusting = false;` variable. In the `treeView_AfterCheck` method put `if (isAdjusting) return; isAdjusting = true;` and then set `isAdjusting = false;` at the end. – Loathing Jul 20 '20 at 07:05
  • https://stackoverflow.com/a/58547452/14171304 – dr.null Sep 22 '20 at 10:25

0 Answers0