January 14, 2009

ASP.NET TreeView - Keep only one parent node expanded




A user recently asked me on the ASP.NET forums on how to expand only one parent node at a time. When the user clicks on a parent node, the ones that are already expanded (if any) should collapse. The answer to this question lies in the TreeNodeExpanded event as shown below:

TreeView markup


<asp:TreeView ID="TreeView1" runat="server" 

    ExpandDepth = "0" 

    ontreenodeexpanded="TreeView1_TreeNodeExpanded">

 <Nodes>

  <asp:TreeNode Text="Managers">

    <asp:TreeNode Text="Scott" Value="EID-XY34E" />

    <asp:TreeNode Text="Brinda" Value="EID-34D78" />

    <asp:TreeNode Text="Kathy" Value="EID-563D1" />

  </asp:TreeNode>

  <asp:TreeNode Text="Accounts">

    <asp:TreeNode Text="Laura" Value="EID-QQ21E" />

    <asp:TreeNode Text="Jemmica" Value="EID-YUR78" />

    <asp:TreeNode Text="Nicole" Value="EID-TG331" />

  </asp:TreeNode>

  <asp:TreeNode Text="Admin">

    <asp:TreeNode Text="Jack" Value="EID-PO41E" />

    <asp:TreeNode Text="Victor" Value="EID-HYR78" />

    <asp:TreeNode Text="Broady" Value="EID-KL931" />

  </asp:TreeNode>

</Nodes>

</asp:TreeView>



C#


protected void TreeView1_TreeNodeExpanded(object sender, 

    TreeNodeEventArgs e)

{

    string currValue = e.Node.Value.Trim();

    foreach (TreeNode tnode in TreeView1.Nodes)

    {

        if (tnode.Value != currValue)

        {

            tnode.Collapse();

        }

    }

}



VB.NET


    Protected Sub TreeView1_TreeNodeExpanded( _

    ByVal sender As Object, ByVal e As TreeNodeEventArgs)

        Dim currValue As String = e.Node.Value.Trim()

        For Each tnode As TreeNode In TreeView1.Nodes

            If tnode.Value <> currValue Then

                tnode.Collapse()

            End If

        Next tnode

    End Sub



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "ASP.NET TreeView - Keep only one parent node expanded"
  1. sanjin said...
    September 9, 2009 2:29 AM

    i also want to expand the contents of that parent without it closing, only when another parent is clicked i want the prevoius 1 to close.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions