I'm trying to fully understand the WebForm event model (not the page lifecycle, but how the events are wired up when specified declaratively in the .aspx or .ascx files.
Take the Button control for example. It has a Click event that you can wire to in the code-behind, but it has an "OnClick" event in the .aspx/.ascx file.
I used the .NET Reflector and the Button control has a PROTECTED OnClick method, but that shouldn't be available to be assigned by the .aspx/.ascx. Unless I'm missing something.
Does anyone know why the "On" prefix is added?
Just to clarify a bit: I understand the naming convention works. I'd like to know how the "OnClick" in the .aspx/.ascx gets translated into .Click += new EventHandler(blahName); I.e. if I create a ControlChanged EventHandler, do I need to do anything special to get the OnControlChanged to show up validly in the .aspx/.ascx file?
Those store references to the delegates that the calling code will be wiring up using events; in order to distinguish between the event itself, and the delegate.
It's more than a naming convention because events in user controls automatically get the "On" prefix in the declarative syntax.
For example, I have a UserControl that declares a ProjectSelected event. To add a handler declaratively, I set the OnProjectSelected attribute.
UserControl:
public event EventHandler<ProjectSelectedEventArgs> ProjectSelected;
Adding handler declaratively:
<user:ProjectList id="uxProjectList" runat="server"
OnProjectSelected="uxProjectList_ProjectSelected" />
Adding handler in code behind:
uxProjectList.ProjectSelected += uxProjectList_ProjectSelected;
This confused the hell out of me twice, once when I couldn't figure out why the event wasn't available declaratively, and again when I named the event "OnProjectSelected" and the attribute became "OnOnProjectSelected".
It's just a naming convention used when raising events. OnSomethingHappened ... OnClick, OnChange, OnClose. I don't think there is anything magical or sinister, it's just a convention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With