Collapse all other treeview nodes when you expand a node

Some people ask themselves the question how can I let all the other opened (expanded) nodes close (collapse) when I open a certain node. Well a very simple easy way to do this is to hook up the TreeNodeExpanded event for the treeview control.

Select your treeview control, in the properties page, select the lightning bolt (events) or type the event part manually in your asp.net code. Your treeview should look something like beneath:

<asp:TreeView ID="tvwItems" runat="server" OnTreeNodeExpanded="tvwItems_OnTreeNodeExpanded"></asp:TreeView>

Now go to your code behind file. If you set your event from the properties page, then there will be a new method inserted for you. If you set the event manually then you have to type the method also, manually. The method has to have the following code:

protected void tvwItems_OnTreeNodeExpanded(object sender, TreeNodeEventArgs e) { foreach (TreeNode tn in tvwItems.Nodes) { if(tn != e.Node && tn.Expanded==true) tn.Collapse(); } }

Ok now when you open a certain node in the treeview all the other opened (expanded) nodes will be closed!


No comments yet. Be the first.

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word