Joe Rosselli

Joe Rosselli

  • NA
  • 5
  • 10.7k

TreeView's 'After Check' event problem .... frustrated

Mar 24 2011 8:46 PM
Running C# and Windows 7. All I want to do is have a checked treeview where when you check a parent node, all subnodes become checked, and same with unchecking.

Microsoft gives example code that supposedly does just this:
http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.aftercheck.aspx

I created a brand new solution with a single form and added a single checked treeview to the form. I directly added the code from that link. This is all of the code I'm running (I apologize if this formats wrong):

[code]
public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();

  TreeNode parentNode = new TreeNode("parent");
  TreeNode subNode1 = new TreeNode("subnode1");
  TreeNode subNode2 = new TreeNode("subnode2");

  parentNode.Nodes.Add(subNode1);
  parentNode.Nodes.Add(subNode2);

  treeView1.Nodes.Add(parentNode);

  treeView1.AfterCheck += node_AfterCheck;
  }

private void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked)
  {
  foreach (TreeNode node in treeNode.Nodes)
  {
  node.Checked = nodeChecked;
  if (node.Nodes.Count > 0)
  {
  this.CheckAllChildNodes(node, nodeChecked);
  }
  }
  }

private void node_AfterCheck(object sender, TreeViewEventArgs e)
  {
  if (e.Action != TreeViewAction.Unknown)
  {
  if (e.Node.Nodes.Count > 0)
  {
  this.CheckAllChildNodes(e.Node, e.Node.Checked);
  }
  }
  }
  }
[/code]

It seems to work as intended. Check the parent node, children become checked.

Problem is ..... try toggling the parent node at any fast speed whatsoever and it instantly becomes unsynced check-wise with its children. Can have the parent checked and children unchecked and vice versa. Completely breaks. I've spent at least 2-3 hours trying to fix this and I can't find any way. I don't know why this type of functionality isn't built in, it's a pretty standard thing for a checked treeview to do ...

I think the problem might have to do with double clicks if that helps at all. The event for double clicks seems all messed up. I can double click a checkbox and the double click wont fire until I SINGLE click the checkbox again ... at ANY time in the future. This also makes no sense whatsoever.

Any help is much appreciated, I'm really burned out and frustrated with this :(

Answers (4)