Capturing the Click event on a Selected TreeView node
September 20th, 2008So this is a little off topic for me, but I have been following stackoverflow for a while and just answered a question on this topic and thought I might as well get some use out of the screen shot.
The method I describe is server-side. There is probably a cool client side javascript hack that also be done, but I tend to think server-side so here it is.
The Page_Load event handler is called with every postback. So I propose adding logic in it to compare the currently selected value to the value stored in the last SelectedNodeChanged event handler.
Here is the screen shot:

Here is the HTML:
-
<form id="form1" runat="server">
-
<asp:TreeView ID="TreeView1" runat="server" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged"
-
ShowLines="True">
-
<Nodes>
-
<asp:TreeNode Text="Root" Value="Root">
-
<asp:TreeNode Text="RootSub1" Value="RootSub1"></asp:TreeNode>
-
<asp:TreeNode Text="RootSub2" Value="RootSub2"></asp:TreeNode>
-
</asp:TreeNode>
-
<asp:TreeNode Text="Root2" Value="Root2">
-
<asp:TreeNode Text="Root2Sub1" Value="Root2Sub1">
-
<asp:TreeNode Text="Root2Sub1Sub1" Value="Root2Sub1Sub1"></asp:TreeNode>
-
</asp:TreeNode>
-
<asp:TreeNode Text="Root2Sub2" Value="Root2Sub2"></asp:TreeNode>
-
</asp:TreeNode>
-
</Nodes>
-
</asp:TreeView>
-
<asp:Label ID="Label1" runat="server" Text="Selected"></asp:Label>
-
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
-
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
-
</form>
and here is the C#:
-
protected void Page_Load(object sender, EventArgs e)
-
{
-
if(TreeView1.SelectedNode!=null && this.TextBox1.Text == TreeView1.SelectedNode.Value.ToString())
-
{
-
Label2.Text = (int.Parse(Label2.Text) + 1).ToString();
-
}
-
else
-
{
-
Label2.Text = "0";
-
}
-
}
-
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
-
{
-
this.TextBox1.Text = TreeView1.SelectedNode.Value.ToString();
-
}