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:
Thank a milion!!!!
Just what i needed! Thanks!
This is brilliant, just what I needed too. Many thanks!
Excellent! Thanks mate :)
good to know.
But to use the new class in aspx file
"< asp: TreeView>....."
Excellent!!!
I'v looking for this a lot of hours!
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?
Can I use your control in a webpart I offer for free, or maybe codeplex?
I will give credit to you.
Rayone: sure!
Hi Per.
I created a codeplex project here: http://wan.codeplex.com/
Let me know if you want to be a member.
Select method for treeview node selection
Post a Comment