1
votes

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.

3

3 Answers

1
votes

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();
    }
}
0
votes

Check the methods Collapse(), CollapseAll(), Expand(), and ExpandAll() of treeview node.

treeView1.SelectedNode.Collapse();

Read Collapse, CollapseAll and Expand on MSDN.

0
votes

Building on Ria's solution, we can collapse both sibling and each sibling's child nodes using recursion. The following works for WPF:

    private void CollapseAll(ItemsControl Items, bool Collapse)
    {
        foreach (object obj in Items.Items)
        {
            ItemsControl ChildControl = Items.ItemContainerGenerator.ContainerFromItem(obj) as ItemsControl;
            if (ChildControl != null)
            {
                CollapseAll(ChildControl, Collapse);
            }
            TreeViewItem Item = ChildControl as TreeViewItem;
            if (Item != null) Item.IsExpanded = false;
        }
    }

    private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        TreeViewItem CurrentItem = (TreeViewItem)treeView1.SelectedItem;
        if (CurrentItem == null) return;
        if (!(CurrentItem.Parent is TreeViewItem)) return;
        TreeViewItem Parent = (TreeViewItem)CurrentItem.Parent;
        if (Parent == null) return;
        foreach (TreeViewItem TreeViewItem in Parent.Items)
        {
            if (TreeViewItem != CurrentItem)
            {
                CollapseAll(TreeViewItem, true);
                TreeViewItem.IsExpanded = false;
            }
        }
    }
}