Title: Check a TreeView subtree in C#
Sometimes it's useful to let the user select a TreeView subtree by clicking on a higher-level node. Then the user can deselect individual nodes within the subtree if desired.
For example, in the picture shown here I checked the Dinner box and the program checked all of the items in the Dinner TreeView subtree. I then deselected the Wine and Dessert items. Deselecting Dessert also deselected all of the items in its TreeView subtree.
When the user checks or unchecks a node, the following AfterCheck event handler executes. (This event fires whenever a checkbox's value changes, except it only fires once if you double-click a node. This doesn't match the way the checkboxes work but it's the behavior of the control so I'm not going to try to fight it.)
// Check or uncheck all nodes in this node's subtree.
private void trvMeals_AfterCheck(object sender, TreeViewEventArgs e)
{
TreeNode node = e.Node;
bool is_checked = node.Checked;
foreach (TreeNode child in node.Nodes)
child.Checked = is_checked;
trvMeals.SelectedNode = node;
}
This code gets the node that was checked or unchecked and saves its Checked state in the variable is_checked to make the code easier to read. It then loops over the node's child nodes and sets all of their Checked properties to match.
When the program changes a child node's Checked state, that node raises an AfterCheck event so the event handler executes for that node, too, and it sets the Checked property for the child's children.
The event handler calls itself recursively until the event handler reaches a node with no children. At that point there is no more recursion and control unwinds back up the call stack.
Download the example to experiment with it and to see additional details.
|