Archive for September, 2008

Capturing the Click event on a Selected TreeView node

Saturday, September 20th, 2008

So 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:
Screen snippit of example

Here is the HTML:

HTML:
  1. <form id="form1" runat="server">
  2.     <div>
  3.         <asp:TreeView ID="TreeView1" runat="server" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged"
  4.             ShowLines="True">
  5.             <Nodes>
  6.                 <asp:TreeNode Text="Root" Value="Root">
  7.                     <asp:TreeNode Text="RootSub1" Value="RootSub1"></asp:TreeNode>
  8.                     <asp:TreeNode Text="RootSub2" Value="RootSub2"></asp:TreeNode>
  9.                 </asp:TreeNode>
  10.                 <asp:TreeNode Text="Root2" Value="Root2">
  11.                     <asp:TreeNode Text="Root2Sub1" Value="Root2Sub1">
  12.                         <asp:TreeNode Text="Root2Sub1Sub1" Value="Root2Sub1Sub1"></asp:TreeNode>
  13.                     </asp:TreeNode>
  14.                     <asp:TreeNode Text="Root2Sub2" Value="Root2Sub2"></asp:TreeNode>
  15.                 </asp:TreeNode>
  16.             </Nodes>
  17.         </asp:TreeView>
  18.         <asp:Label ID="Label1" runat="server" Text="Selected"></asp:Label>
  19.         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  20.         <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
  21.     </form>

and here is the C#:

C#:
  1. protected void Page_Load(object sender, EventArgs e)
  2.     {
  3.         if(TreeView1.SelectedNode!=null && this.TextBox1.Text == TreeView1.SelectedNode.Value.ToString())
  4.         {
  5.             Label2.Text = (int.Parse(Label2.Text) + 1).ToString();
  6.         }
  7.         else
  8.         {
  9.             Label2.Text = "0";
  10.         }
  11.     }
  12.     protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
  13.     {
  14.         this.TextBox1.Text = TreeView1.SelectedNode.Value.ToString();
  15.     }