jQuery and ASP.NET

May 28, 2009

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"


        ontreenodeexpanded="TreeView1_TreeNodeExpanded">


        <Nodes>


            <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>


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


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


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


            </asp:TreeNode>


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


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


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


            </asp:TreeNode>


        </Nodes>


</asp:TreeView>




C#


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


            treenode.Collapse();    


        }


    }


}




VB.NET


    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


                treenode.Collapse()


            End If


        Next treenode


    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

0 Responses to "Collapse all Open Nodes Of an ASP.NET TreeView when Another Node is expanded"
 

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