In this article I will explain with an example, how to handle TreeView node onclick event on client side using JavaScript in C# and VB.Net.
 
 
HTML Markup
The following HTML Markup consists of:
TreeView – For displaying data.
The TreeView consists of the SelectedNodeStyle property.
<asp:TreeView ID="tvFruits" runat="server">
    <SelectedNodeStyle ForeColor="Black" />
</asp:TreeView>
 
 
Handle node onclick event on client side using JavaScript
Inside, the OnLoad JavaScript function, the Nodes of the TreeView is referenced using dynamically generated identifier.
A FOR loop is executed over the referenced nodes and HREF attribute is replaced with custom JavaScript function NodeClick JavaScript function.
 
NodeClick
Inside the NodeClick JavaScript function, the Text of the clicked Node is displayed using JavaScript Alert Message Box.
<script type="text/javascript">
    function OnLoad() {
        var links = document.getElementById("<%=tvFruits.ClientID %>").getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            links[i].setAttribute("href", "javascript:NodeClick(\"" + links[i].id + "\", \"" + links[i].getAttribute("href") + "\")");
        }
    }
    window.onload = OnLoad;
    function NodeClick(id, attribute) {
        //Do Something
        var nodeLink = document.getElementById(id);
        alert(nodeLink.innerHTML + " clicked");
 
        //Execute the server side event.
        eval(attribute);
    }
</script>
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Web.UI.WebControls;
 
VB.Net
Imports System.Web.UI.WebControls
 
 
Populating TreeView
Inside the Page_Load event handler, the name and value of the fruits are added as Node to the TreeView.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        tvFruits.Nodes.Add(new TreeNode("Mango", "Fruit 1"));
        tvFruits.Nodes.Add(new TreeNode("Apple", "Fruit 2"));
        tvFruits.Nodes.Add(new TreeNode("Pineapple", "Fruit 3"));
        tvFruits.Nodes.Add(new TreeNode("Orange", "Fruit 4"));
        tvFruits.Nodes.Add(new TreeNode("Grapes", "Fruit 5"));
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        tvFruits.Nodes.Add(New TreeNode("Mango", "Fruit 1"))
        tvFruits.Nodes.Add(New TreeNode("Apple", "Fruit 2"))
        tvFruits.Nodes.Add(New TreeNode("Pineapple", "Fruit 3"))
        tvFruits.Nodes.Add(New TreeNode("Orange", "Fruit 4"))
        tvFruits.Nodes.Add(New TreeNode("Grapes", "Fruit 5"))
    End If
EndSub
 
 
Screenshot
ASP.Net TreeView - Handle node onclick event client side using JavaScript
 
 
Demo
View Demo
 
 
Downloads