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" 



  <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 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 Text="Admin">

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

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

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





protected void TreeView1_TreeNodeExpanded(object sender, 

    TreeNodeEventArgs e)


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

    foreach (TreeNode tnode in TreeView1.Nodes)


        if (tnode.Value != currValue)







    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


            End If

        Next tnode

    End Sub

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

sanjin said...

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.