views:

202

answers:

2

Hello,


Q1:

“The ListControl.OnSelectedIndexChanged method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.”


A) If I understand the above quote, then if we derive a class from ListControl, we should instead of subscribing to SelectedIndexChanged event, treat OnSelectedIndexChanged() method as an event handler and thus put any event processing logic inside it:

protected override void OnSelectedIndexChanged(
EventArgs e
{
   //event handling logic
}

Why would that be better than subscribing to an event(inside .aspx) via OnSelectedIndexChanged = ”name_of_event_handler”?


B) Anyways, in ascx file we use OnSelectedIndexChanged attribute to attach event handler to an event. Name of this attribute is the same as the name of OnSelectedIndexChanged() method. Why is that? Why isn't instead the name of this attribute SelectedIndexChanged:

 <asp:ListControl SelectedIndexChanged = ”name_of_event_handler”

Afterall, attribute refers to an event and not to a method ( OnSelectedIndexChanged() ) that calls this event!


thanx


EDIT:

Hello,

HOWEVER, be sure that you call base.On[EventName] or the event won't fire!

Assuming you don’t want anyone else to be able to respond to this event, then would it be perfectly OK not to call base.On[EventName], since I would think not calling it won’t really do any harm besides not firing an event ( and thus event handlers won't be called )?

I realize some events need to be fired in order for Framework to do its job, but what about not calling base.On[SelectedIndexChanged]?

+1  A: 

In general, I prefer to override the On[EventName] functions so that I can control if my logic happens before or after the logic in any subscribers.

HOWEVER, be sure that you call base.On[EventName] or the event won't fire!

Adam Robinson
+3  A: 

It is "better" in that:

  • it is cheaper to use virtual (inheritance) where possible - it removes the need for a few extra objects (delegate instances, etc)
  • it allows the overriding code to know where it comes in the sequence - i.e. if multiple callers are listening, does it fire first? second? in the middle?

The first point is arguably more important for efficiency, especially in things like controls that have sparse event handlers (i.e. things like EventHandlerList instead of a field-like-event).

I don't really understand the second question, but at a guess: convention.

Marc Gravell