Tuesday, May 25, 2010

ASP.Net TreeView SelectedNodeChanged doesn't fire!

Well, there are a lot of good reasons why that could happen because of your bad code, but this time it is a plain ugly Microsoft bug. You see, the code in the RaisePostBackEvent method in the TreeView control first checks if the control has an Adapter and if not, it just does its thing. If there is an Adapter, it tries to cast it to a IPostBackEventHandler and then fires the RaisePostBackEvent event there. However, if the TreeView control has an adapter and it is not a RaisePostBackEvent, nothing happends!

Here is the offending code:

protected virtual void RaisePostBackEvent(string eventArgument)
base.ValidateEvent(this.UniqueID, eventArgument);
if (base.IsEnabled)
if (base._adapter != null)
IPostBackEventHandler handler =
base._adapter as IPostBackEventHandler;
if (handler != null)
else ...

Bottom line, you need to either not use an adapter for the TreeView, or use one that knows how to handle the postback. And given the complexity of the code in the method, it is better to just not use an adapter.

The solution I have adopted is to recreate the functionality in an override of the RaisePostBackEvent method and add some more (like TreeNodeClicked and SelectedNodeClicked). Hint: you need to also get in LoadPostData and remember which nodes are selected in order to check if the selected node has changed.


rams said...

hi! i read your find on the bug. do you have any working example to work around this problem?
P.S. neither selectednodechanged nor treenodecheckchanged events work.

David Grider said...

Thanks, this helped me quite a bit! I've spent the last two days trying to figure how how to fix it.