TreeView CheckBox check Association, treeviewcheckbox
The TreeView control is used in the C # Winform project and must be checked. The implementation of parent-child node linkage is as follows:
1. When a parent node is selected, if its child node is not selected, it is selected.
2. When the parent node is deselected, all child nodes are deselected.
3. When you select a subnode, You need to determine whether all the child nodes in its parent node have been selected. If all are selected, select the parent node.
4. When canceling a child node, You need to determine whether the parent node has been selected. If yes, the parent node is deselected.
Note: All nodes may be both parent and child nodes. For example, if effect 3 is met and the parent node is selected, the parent node has its own parent node, and the result 3 needs to be executed again.
If we have processed a node, the parent node associated with the node, and the parent node of the parent node ,..., and the child nodes of the node, and the child nodes of the node ..., A coordinated response is triggered. So I used recursion to solve this problem.
TreeView has an event: AfterCheck. We do not need to name a new recursion, but directly use this event. When a node is selected, this event will be entered. When the node is selected using code in this event, this event is also triggered. The AfterCheck parameter is the selected node .; This is recursion when I select nodes in association.
Check the node linkage code. You only need to write the code in the AfterCheck event to achieve the effect. The following is the code without comments:
Private void treeviewappsaftercheck (object sender, TreeViewEventArgs e)
{
Try
{
If (e. Node. Nodes. Count> 0)
{
Bool NoFalse = true;
Foreach (TreeNode tn in e. Node. Nodes)
{
If (tn. Checked = false)
{
NoFalse = false;
}
}
If (e. Node. Checked = true | NoFalse)
{
Foreach (TreeNode tn in e. Node. Nodes)
{
If (tn. Checked! = E. Node. Checked)
{
Tn. Checked = e. Node. Checked;
}
}
}
}
If (e. Node. Parent! = Null & e. Node. Parent is TreeNode)
{
Bool ParentNode = true;
Foreach (TreeNode tn in e. Node. Parent. Nodes)
{
If (tn. Checked = false)
{
ParentNode = false;
}
}
If (e. Node. Parent. Checked! = ParentNode & (e. Node. Checked = false | e. Node. Checked = true & e. Node. Parent. Checked = false ))
{
E. Node. Parent. Checked = ParentNode;
}
}
}
Catch (Exception ex)
{
}
}
I have already written a lot of details above, so I will not write any comments.