TreeView Checkbox Click on PostBack

Friday, May 7, 2010

The TreeView control admitted in ASP.Net 2.0 is lacking an option to cause a postback due to a user checking/unchecking a checkbox on a tree node.

It would of course be useful to add a bit more code so that the resulting event could specify which node was changed, etc.  But as of now you can just look at the "checkednodes" property of the tree.

 

Code Snippet
  1. using System;
  2. using System.Text;
  3. using System.Data;
  4. using ASP = System.Web.UI.WebControls;
  5. using System.Web.UI;
  6. using System.IO;
  7.  
  8. namespace myNameSpace
  9. {
  10.     class VerboseTreeView : ASP.TreeView, IPostBackEventHandler
  11.     {
  12.         public event EventHandler CheckClick;
  13.  
  14.          protected override void Render(HtmlTextWriter writer)
  15.         {
  16.             StringBuilder builder = new StringBuilder();
  17.  
  18.             using(StringWriter stringWriter = new StringWriter(builder))
  19.             {
  20.                 HtmlTextWriter tempWriter = new HtmlTextWriter(stringWriter);
  21.                 base.Render(tempWriter);
  22.             }
  23.  
  24.             string find = "<input type=\"checkbox\" ";
  25.             string replace = "<input type=\"checkbox\\cf2 " onClick=\"" + getPostBack() + "\\cf2 " ";
  26.  
  27.             writer.Write(builder.ToString().Replace(find, replace));
  28.         }
  29.  
  30.         protected string getPostBack()
  31.         {
  32.             return this.Page.GetPostBackEventReference(this, "@CheckPostBack");
  33.         }
  34.  
  35.         protected virtual void OnCheckClick(EventArgs e)
  36.         {
  37.             if (CheckClick != null) CheckClick(this, e);
  38.         }
  39.  
  40. void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
  41.         {
  42.             OnCheckClick(new EventArgs());
  43.         }
  44.  
  45.     }
  46. }
  47.  
  48. Be the first to rate this post
  49.  
  50.     * Currently 0/5 Stars.
  51.     * 1
  52.     * 2
  53.     * 3
  54.     * 4
  55.     * 5
  56.  
  57.     ShareThis
  58. Tags:
  59.        }

Posted by Rahul at 4:56 AM  

0 comments:

Post a Comment

Website Updates