Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do WebControl events have the prefix of "On"?

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?

like image 708
Jared Avatar asked Jun 17 '09 00:06

Jared


3 Answers

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.

like image 71
Jason Watts Avatar answered Nov 15 '22 07:11

Jason Watts


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".

like image 4
Jamie Ide Avatar answered Nov 15 '22 09:11

Jamie Ide


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.

like image 2
JP Alioto Avatar answered Nov 15 '22 07:11

JP Alioto