Add TreeView TreeNode programmatically
asp.net 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.
TreeViewAddRemoveNode.aspx
<%@ 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() +
"Example.aspx";
newNode.ToolTip = TextBox1.Text.ToString() +
" Example";
TreeView1.FindNode("Home/StandardToolBox").ChildNodes.Add(newNode);
Label1.Text = "Node Added succesfully!" +
"<br />Node Text: " + TextBox1.Text.ToString() +
"<br />NavigateUrl: " + TextBox1.Text.ToString() + "Example.aspx" +
"<br />ToolTip: " + TextBox1.Text.ToString() + " Example";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Asp.Net TreeView example: how to add TreeNode programmatically</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<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">
</asp:TreeView>
<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" />
</div>
</form>
</body>
</html>
Web.sitemap
Web.sitemap file source code is here Web.sitemap

