Collapse all Open Nodes Of an ASP.NET TreeView when Another Node is expanded

Users have a very common requirement around the ASP.NET TreeView - that is to keep only one TreeNode expanded at a given point of time. So if a TreeNode in the TreeView is expanded, collapse the other open TreeNodes. Here's how to do so:

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



            <asp:TreeNode Text="Node1" Value="Node1">

                <asp:TreeNode Text="Node1.1" Value="Node1.1"/>

                <asp:TreeNode Text="Node1.2" Value="Node1.2"/>

                <asp:TreeNode Text="Node1.3" Value="Node1.3"/>


            <asp:TreeNode Text="Node2" Value="Node2">

                <asp:TreeNode Text="Node1.1" Value="Node2.1"/>

                <asp:TreeNode Text="Node1.2" Value="Node2.2"/>


            <asp:TreeNode Text="Node3" Value="Node3">

                <asp:TreeNode Text="Node3.1" Value="Node3.1"/>

                <asp:TreeNode Text="Node3.2" Value="Node3.2"/>





protected void TreeView1_TreeNodeExpanded(object sender, TreeNodeEventArgs e)


    // Loop through all nodes

    foreach (TreeNode treenode in TreeView1.Nodes)


        // If node is expanded

        if (treenode != e.Node)


            // Collapse all other nodes






    Protected Sub TreeView1_TreeNodeExpanded(ByVal sender As Object, ByVal e As TreeNodeEventArgs)

        ' Loop through all nodes

        For Each treenode As TreeNode In TreeView1.Nodes

            ' If node is expanded

            If treenode IsNot e.Node Then

                ' Collapse all other nodes


            End If

        Next treenode

    End Sub

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Unknown said...

Thank you so much! This is what i exactly expect....