C# – Collapse Other Nodes of TreeView on Selection of One Node

ctreeviewvisual-studio-2008winforms

I have a treeview control on *winform applica*tion. Here, what I want to do is:
Collapse all other nodes at his level and expend only selected node.
For example, suppose the scenario:
– All Subject
+ Computer Science
+ Mathematics

Root Node is "All Subjects" and two child nodes are 1) Computer Science and 2) Mathematics.
These two child nodes have further child nodes.

When I select Computer Science, teh Mathematic node should be collapsed and Computer Science Node should be expanded.
How can this be achieved ?
Suggestion to accomplish this are welcomed.

Best Answer

EDIT (thanks Hans Passant) Handel AfterSelect or BeforeSelect events, and collapse other sibling nodes. like this:

private void TreeViewAfterSelect(object sender, TreeViewCancelEventArgs e)
{
    foreach (TreeNode node in e.Node.Parent.Nodes)
    {
        if(node != e.Node)
            node.Collapse();
    }
}
Related Topic