Add TreeNode programmatically in TreeView

Add TreeView TreeNode programmatically treeview web server control is used to display hierarchical data. we can populate a display from SiteMapDataSource. we can even populate treeview by static data using declarative syntax. treeview have built in methods to add or remove node programmatically. to add a node in a treeview specific position, we need to first find the node and add new node as a child node of that parent node. in this example code, we added a node as navigation mode. so we set values for node Text and NavigateUrl property. the entire process is very simple. first create a new tree node then add it as child node under specific node.

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

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        TreeNode newNode = new TreeNode();
        newNode.Text = TextBox1.Text.ToString();
        newNode.NavigateUrl = TextBox1.Text.ToString() +
        newNode.ToolTip = TextBox1.Text.ToString() +
            " Example";
        Label1.Text = "Node Added succesfully!" +
            "<br />Node Text: " + TextBox1.Text.ToString() +
            "<br />NavigateUrl: " + TextBox1.Text.ToString() + "Example.aspx" +
            "<br />ToolTip: " + TextBox1.Text.ToString() + " Example";

<html xmlns="">
<head runat="server">
    <title>Asp.Net TreeView example: how to add TreeNode programmatically</title>
    <form id="form1" runat="server">
        <h2 style="color:Red">Dynamically adding TreeNode</h2>
        <asp:Label ID="Label1" runat="server" Font-Bold="true" ForeColor="Teal"></asp:Label>
        <br /><br />
        <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
        <asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1">
        <br /><br />
        <asp:Label ID="Label2" runat="server" Text="Node [StandardToolBox Control Name]"></asp:Label>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Add Node" OnClick="Button1_Click" />
Web.sitemap file source code is here Web.sitemap

Related example