Check a TreeView subtree in C#

[TreeView subtree]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, user interface and tagged , , , , , , , , , , , , . Bookmark the permalink.

4 Responses to Check a TreeView subtree in C#

  1. SAM says:

    Good Post!

    Thanks

  2. myName says:

    thanks, great article would you please tell us how to get a list of all checked items and display them in a listview?

Leave a Reply

Your email address will not be published. Required fields are marked *