27

I have a TreeView on my form but I'd like it to always be fully expanded, even the child nodes.

Is there a way?

8 Answers 8

35

Do you want it to initially display expanded? If so, then call the ExpandAll method on the root node after you have added all of the tree nodes.

If you want it to display expanded and not allow the user to collapse it, then you need to handle the BeforeCollapsed event and cancel it. (Set e.Cancel = true;).

2
  • Actually it does not have to be after adding all the tree nodes, but at least one. This is useful information if you have a tree that will always be updated.
    – kdmin
    Aug 1, 2014 at 20:24
  • @kdmin: I think you would always want to call ExpandAll() after all of the tree nodes have been added so that the expansion happens after the control initialization occurs; otherwise I think the state of the nodes can get out of sync. Aug 4, 2014 at 19:51
7

One way is to use TreeView.ExpandAll() like this:

private void myCheckBox_CheckedChanged(object sender, System.EventArgs e)
{
   // If the check box is checked, expand all the tree nodes.
   if (myCheckBox.Checked == true)
   {
      myTreeView.ExpandAll();
   }
   else
   {
      myTreeView.CollapseAll();
   }
}
6

In WPF, one way is to keep your tree view fully expanded:

<TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="IsExpanded" Value="True" />
    </Style>
</TreeView.ItemContainerStyle>
1
  • Thanks for your comment @IgnacioAra, Its updated now to text. May 23, 2018 at 7:21
3

Guessing here... On the BeforeCollapsed event, set e.Cancel = true;

1
  • Probably a combination of what I said plus what Ashton said. Is this for a WinForm or a WebForm? I think they both have a TreeView control. May 11, 2010 at 19:46
1

TreeView.ExpandAll Method

1

Try the TreeNode.EnsureVisible Method - [1]: https://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.ensurevisible(v=vs.90).aspx

0
0

Use this code:

private void ManagerFolder_Load(object sender, EventArgs e)
{
    treeView.ExpandAll();
    treeView.Nodes[0].FirstNode.Collapse();
    treeView.Nodes[4].FirstNode.Collapse();
}
0

You may be wondering where to put the treeview1.expandAll() statement? You cannot put it in the Designer's generated code, or it will be deleted at the next form refresh/save.

I've put it in the "Form1.cs" code, in the partial class part which deals with the form initialization, and it works. Just after the InitializeComponent() statement (if you don't know what I'm talking about, just find that statement)

Hope it helps :)

PD. Thanks for your support, you're great, guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.