Expand and Collapse TreeNode programmatically in asp.net TreeView

Expand and Collapse TreeView TreeNode programmatically
treeview is used to display hierarchical data. this web server control is made up of one or more nodes. nodes are different types such as root node, parent node, child node and leaf node. we can expand or collapse root nodes, parent nodes and child nodes. treeview control have default image set to use as expand and collapse image button. when we click expand or collapse image then the treeview control expand or collapse it's specific nodes.

we can also expand or collapse tree node programmatically using c# script section. following example code demonstrate us how we can expand or collapse tree nodes programmatically. here we uses two button control to programmatically expand and collapse all tree nodes in a treeview control. in this example we uses treeview ExpandAll and CollapseAll method.

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {

    protected void Button2_Click(object sender, System.EventArgs e) {

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Asp.Net TreeView example: expand, collapse TreeNode programmatically</title>
    <form id="form1" runat="server">
        <h2 style="color:Red">TreeView Exapnd Collapse Example</h2>
        <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
        <asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" 
            ImageSet="XPFileExplorer" NodeIndent="15">
            <ParentNodeStyle Font-Bold="False" />
            <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
            <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" 
                HorizontalPadding="0px" VerticalPadding="0px" />
            <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" 
                HorizontalPadding="2px" NodeSpacing="0px" VerticalPadding="2px" />
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Expand" OnClick="Button1_Click" Font-Bold="true" ForeColor="Red" />
        <asp:Button ID="Button2" runat="server" Text="Collapse" OnClick="Button2_Click" Font-Bold="true" ForeColor="Red" />
Web.sitemap file source code is here Web.sitemap

More asp.net example