Why is there a "On" prefix in WebControl events?

I am trying to fully understand the WebForm event model (and not the page life cycle, but how events get connected if declaratively specified in .aspx or .ascx files.

Take a Button control, for example. It has a Click event that you can connect to the code, 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 it should not be available for .aspx / .ascx assignment. If I didn’t miss something.

Does anyone know why the prefix "On" is added?

Just to clarify a bit: I understand that the naming convention works. I would like to know how "OnClick" in .aspx / .ascx is converted to .Click + = new EventHandler (blahName); That is, if I create a ControlChanged EventHandler, do I need to do something special to make OnControlChanged display correctly in the .aspx / .ascx file?

+6
events webforms
source share
4 answers

This is more than a naming convention because events in user controls automatically get the prefix “On” in 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 a handler declaratively:

  <user:ProjectList id="uxProjectList" runat="server" OnProjectSelected="uxProjectList_ProjectSelected" /> 

Adding a handler to the code behind:

  uxProjectList.ProjectSelected += uxProjectList_ProjectSelected; 

This drove me crazy twice when I couldn't understand why the event was not available declaratively, and again when I called the event “OnProjectSelected” and the attribute became “OnOnProjectSelected”.

+4
source share

Those store links to delegates that the calling code will connect to events; to distinguish between an event and a delegate.

+6
source share

This is just a naming convention used when raising events. OnSomethingHappened ... OnClick, OnChange, OnClose. I don’t think there is anything magical or ominous, it’s just a convention.

+2
source share

Semantically, this is basically an old return to the VB tradition, where event listeners are usually called OnWhatever. Old habits die hard.

0
source share

All Articles