PostBack on TreeView Checkbox Click

The TreeView control included 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.

I hacked together a little derived class to use in place of the treeview that postsback when the user clicks the checkbox, and also fires an event.

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. 

using System;
using System.Text;
using System.Data;
using ASP = System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;

namespace myNameSpace
{
class VerboseTreeView : ASP.TreeView, IPostBackEventHandler
{
public event EventHandler CheckClick;

protected override void Render(HtmlTextWriter writer)
{
StringBuilder builder = new StringBuilder();

using(StringWriter stringWriter = new StringWriter(builder))
{
HtmlTextWriter tempWriter = new HtmlTextWriter(stringWriter);
base.Render(tempWriter);
}

string find = "<input type="checkbox" ";
string replace = "<input type="checkbox" onClick="" + getPostBack() + "" ";

writer.Write(builder.ToString().Replace(find, replace));
}

protected string getPostBack()
{
return this.Page.GetPostBackEventReference(this, "@CheckPostBack");
}

protected virtual void OnCheckClick(EventArgs e)
{
if (CheckClick != null) CheckClick(this, e);
}

void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
OnCheckClick(new EventArgs());
}

}
}
Share This Post!Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>