title: Winforms treeview, recursively check child nodes problem
body: <p>The following code is taken direct from Microsoft at <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.aftercheck%28VS.80%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.aftercheck%28VS.80%29.aspx</a>.</p>
  
  <pre><code>  // Updates all child tree nodes recursively.
    private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
    {
     foreach (TreeNode node in treeNode.Nodes)
     {
      node.Checked = nodeChecked;
      if (node.Nodes.Count &gt; 0)
      {
       // If the current node has child nodes, call the CheckAllChildsNodes method recursively.
       this.CheckAllChildNodes(node, nodeChecked);
      }
     }
    }
  
    // NOTE   This code can be added to the BeforeCheck event handler instead of the AfterCheck event.
    // After a tree node's Checked property is changed, all its child nodes are updated to the same value.
    private void node_AfterCheck(object sender, TreeViewEventArgs e)
    {
     // The code only executes if the user caused the checked state to change.
     if (e.Action != TreeViewAction.Unknown)
     {
      if (e.Node.Nodes.Count &gt; 0)
      {
       /* Calls the CheckAllChildNodes method, passing in the current 
       Checked value of the TreeNode whose checked state changed. */
       this.CheckAllChildNodes(e.Node, e.Node.Checked);
      }
     }
    }
  </code></pre>
  
  <p>You put it in a form containing a treeview and call node_AfterCheck on (surprise, surprise), the treeview AfterCheck event. It then recursively checks or unchecks the child nodes on the treeview.</p>
  
  <p>However if you actually try it, and click several times on the same treeview check box fast enough, the child nodes end up with their check out-of-sync with the parent. You probably need a couple of levels of children with perhaps 100 children in-total for the UI update to be slow enough to notice this happening.</p>
  
  <p>I've tried a couple of things (such as disabling the treeview control at the beginning of node_AfterCheck and re-enabling at the end), but the out-of-sync problem still happens.</p>
  
  <p>Any ideas?</p>