asp.net - Change TreeView parent node style programmatically

TreeView parent node style
The following asp.net c# example code demonstrate us how can we set or change TreeView control's parent node style programmatically at run time in an asp.net application. TreeView is an asp.net web server control. TreeView control allow us to display hierarchical data in a tree structure that has items that can expand and collapse.

We can populate a TreeView with nodes by data binding TreeView control with a data source control such as SiteMapDataSource and XmlDataSource.

TreeView ParentNodeStyle property allow us to design and style all parent nodes in a TreeView control. ParentNodeStyle property have many sub properties. We can set ParentNodeStyle property declaratively in the form Property-Subproperty such as ParentNodeStyle-BackColor or programmatically in the form Property.Subproperty such as ParentNodeStyle.ForeColor.

We can change/set TreeView control's parent nodes background color, text color, text size, font name, font style (bold, italic, underline) etc by using ParentNodeStyle property.
TreeViewParentNodeStyle.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Drawing" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        TreeView1.ParentNodeStyle.BackColor = Color.Crimson;
        TreeView1.ParentNodeStyle.ForeColor = Color.Snow;
        TreeView1.ParentNodeStyle.BorderWidth = 1;
        TreeView1.ParentNodeStyle.BorderColor = Color.HotPink;
        TreeView1.ParentNodeStyle.Font.Italic = true;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to set, change TreeView parent node style programmatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">TreeView Example: ParentNodeStyle</h2>
        <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
        <asp:TreeView 
             ID="TreeView1"
             runat="server"
             DataSourceID="SiteMapDataSource1"
             Width="275"
             BorderWidth="2"
             BorderColor="DodgerBlue"
             >
        </asp:TreeView>
        <br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             ForeColor="SeaGreen"
             Text="Change ParentNodeStyle"
             Height="45"
             OnClick="Button1_Click"
             Font-Bold="true"
             />
    </div>
    </form>
</body>
</html>
Web.sitemap
Web.sitemap source code here.

   
Related asp.net example