Recently, a user asked me to write a demo program to demonstrate how to select a node in the Treeview so that all its child nodes are selected. The parent node changes the status based on the changes of the current node. During implementation, I did this in the aftercheck event of the Treeview. However, if the program has been run, the program overflows. Take a closer look, it turns out that when the checked attribute of a node is modified, the aftercheck event of the Treeview is re-matched, resulting in a chain reaction. Through the event parameters, you can get the action attribute. After viewing msdn, you can find that you should judge the action in the event to avoid chain reactions.
The general method is as follows:
Private void trvdbbinding_aftercheck (Object sender, system. Windows. Forms. treevieweventargs E)
{
If (E. Action! = Treeviewaction. Unknown)
{
// Event call by mouse or key-Press
Setnodecheckstatus (E. node, E. node. Checked );
}
}
Private void setnodecheckstatus (treenode TN, bool checked)
{
If (Tn = NULL) return;
// Check children nodes
Foreach (treenode tnchild in TN. nodes)
{
Tnchild. Checked = checked;
Setnodecheckstatus (tnchild, checked );
}
// Set parent check status
Treenode tnparent = tn;
Int nnodecount = 0;
While (tnparent. parent! = NULL)
{
Tnparent = (treenode) (tnparent. Parent );
Nnodecount = 0;
Foreach (treenode tntemp in tnparent. nodes)
If (tntemp. Checked = checked)
Nnodecount ++;
If (nnodecount = tnparent. nodes. Count)
Tnparent. Checked = checked;
Else
Tnparent. Checked = false;
}
}
Similar events include aftercollapse, afterexpand, and afterselect. To avoid the chain reaction of the event, you must judge the action.