This is just for a better understanding of the ASP.NET framework. When you use a control in a declarative way (that would be web form markup), you assign event handlers by their method name using an attribute that starts with On:
<asp:Button runat="server" OnClick="..."/>
But when you look at the System.Web.UI.WebControls.Button class it has an EventHandler property named Click that the delegate is assigned to:
button.Click += new EventHandler(...);
So how is this implemented? Is that just a convention followed by the parser?
I know, it’s a strange question, the answer will do nothing but satisfy my curiosity.
This is a naming convention used by ASP.NET which, rather unhelpfully, looks identical to another common naming convention widely used throughout .NET. Despite the apparent similarity, these two conventions are unrelated.
The .NET-wide convention, which turns out to be irrelevant here, is that it’s common for events to have corresponding methods that raise the event, and for those methods’ names to be formed by adding an
Onprefix to the event name. For example, theClickevent offered byButtonis related to anOnClickmethod, which raises that event (as has already been stated in another answer here).The confusing part is that the
OnClickmethod has nothing to do with theOnClickattribute that the question concerns.It’s easy to demonstrate that the
OnSomeEventmethods are irrelevant here by writing a control that doesn’t have any such method. Here’s the codebehind for a simple user control:This declares a
Foobarevent. (It never actually raises it, but that doesn’t matter for the purposes of exploration.) It does not define anOnFoobarmethod. Nevertheless, ASP.NET is perfectly happy for us to use theOnSomeEventconvention when we use the control:In fact, it’s not only happy for us to do that, it actually requires it. Even though my control doesn’t define any member called
OnFoobar—the event is called justFoobar—I have to writeOnFoobarif I want to attach the event handler from my.aspxfile. If I just put aFoobarattribute in there in an attempt to attach the event, the handler will never run. (Unhelpfully, ASP.NET doesn’t generate an error when you do that, it just silently fails to do anything with the attribute, and the event handler never runs.)