Friday, January 25, 2008

Custom TreeView with a Select (onclick) event

One thing that disturbs me a bit is that the TreeView control does not have an event that is triggered when the user clicks an already selected item (in my case, I need to know about this so that I can refresh data. The SelectedNodeChanged is never fired when you click on an already selected item).

So wondered if it is possible to create my custom implementation of the TreeView and it turned out to be quite easy to do after a quick check in the reflector

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace GB.ControlLib {

public class GTreeView : System.Web.UI.WebControls.TreeView
{

private static readonly object TreeViewSelected = new object();

public event EventHandler Select
{
add { base.Events.AddHandler(TreeViewSelected, value); }
remove { base.Events.RemoveHandler(TreeViewSelected, value); }
}

protected virtual void OnSelect(EventArgs e)
{
EventHandler handler = (EventHandler)base.Events[TreeViewSelected];
if (handler != null) {
handler(this, e);
}
}

internal void RaiseOnSelect()
{
this.OnSelect(EventArgs.Empty);
}

protected override void RaisePostBackEvent(string eventArgument)
{
base.RaisePostBackEvent(eventArgument);


if (eventArgument.Length != 0) {
char ch = eventArgument[0];
string val = HttpUtility.HtmlDecode(eventArgument.Substring(1));
// Pathseparator in eventArgument is backslash, so we must temporary set the separator
char oldPathSeparator = PathSeparator;
PathSeparator = '\\';
TreeNode node = FindNode(val);
PathSeparator = oldPathSeparator;

if (ch == 's') {
if (node != null) {
if ((node.SelectAction == TreeNodeSelectAction.Select) || (node.SelectAction == TreeNodeSelectAction.SelectExpand)) {
RaiseOnSelect();
}
}
}
}
}


}


}












11 comments:

Anonymous said...

Thank a milion!!!!

Anonymous said...

Just what i needed! Thanks!

Anonymous said...

This is brilliant, just what I needed too. Many thanks!

Anonymous said...

Excellent! Thanks mate :)

Anonymous said...

good to know.
But to use the new class in aspx file

"< asp: TreeView>....."

Alejandro said...

Excellent!!!
I'v looking for this a lot of hours!

pwrgreg007 said...

This works great, however the selected node is not highlighted after postback like it was in the asp:TreeView control. Is there a way to have that default behavior?

rayone said...

Can I use your control in a webpart I offer for free, or maybe codeplex?
I will give credit to you.

Per Gårdebrink said...

Rayone: sure!

rayone said...

Hi Per.

I created a codeplex project here: http://wan.codeplex.com/

Let me know if you want to be a member.

Anonymous said...

Select method for treeview node selection