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






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

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.