BLOG.CSHARPHELPER.COM: Expand a TreeView node's subtree in C#
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.
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.)
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
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