Expand a TreeView node's subtree in C#

A program can call a TreeView node's EnsureVisible method to expand all of the nodes above it in the tree, but there is no simple method to expand an entire subtree below a node. This example uses the following ExpandNode method to expand a node and its subtree.

// Expand this node and its subtree.
private void ExpandNode(TreeNode node)
{
    node.EnsureVisible();
    foreach (TreeNode child in node.Nodes)
    {
        ExpandNode(child);
    }
}

This code calls the node's EnsureVisible method. It then loops through the node's children and recursively calls ExpandNode for each.

That would be the end of the story except a TreeView control can have more than one top-level node. That means if you want to expand the entire tree, you need to call ExpandNode for each top-level node. The following ExpandTreeView method does just that.

// Expand the TreeView control's top-level nodes.
private void ExpandTreeView(TreeView trv)
{
    foreach (TreeNode node in trv.Nodes)
    {
        ExpandNode(node);
    }
}

This method simply loops through the TreeView's top-level nodes, calling ExpandNode for each.

(Note that these methods might make good extension methods for the TreeNode and TreeView classes.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 10/22/2012 12:00 AM Richard Moss wrote:
    Erm... TreeNode.ExpandAll?

    Internally it does pretty much exactly what your example does, but it's built in to the TreeView control itself.
    Reply to this
    1. 10/22/2012 8:22 AM Rod Stephens wrote:
      Oops! I missed that. Both the TreeNode and TreeView classes have this method.

      The next example performs a similar recursion but to do something that I think the control cannot do by itself (I hope).
      Reply to this
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.