Why is it that in .aspx pages all events are preceded with "On
" e.g. "OnClick
", "OnCommand
" and in the code-behind file they are referred "Click
", "Command
"? Just Naming Convention or is there some logical explanation?
views:
138answers:
4Those methods are actually the methods called when the events are raised. Typically they will check if there are any subscribers. It has always been unclear to me why they are virtual.
Take a look at this code for the Button
control.
protected virtual void OnClick(EventArgs e)
{
EventHandler handler = (EventHandler) base.Events[EventClick];
if (handler != null)
{
handler(this, e);
}
}
AFAIK, just naming convention. They had to start with something :-) Prior to ASP.NET I think it was also like this in Windows applications and in JavaScript.
http://www.c-sharpcorner.com/UploadFile/puranindia/165/
http://webdevelopersjournal.com/articles/jsevents1/jsevents1.html
I may have your question wrong, but from what I can tell by what your asking, the EVENT and the PROPERTY cannot have the same name
The event is "Click"... example.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
But in the actual control, there is a property called "OnClick" whereby it activates the "Click" event. Therefor they cannot be named the same thing.
The names of the events themselves are Click, Change, etc... The internal methods to fire those events from code are prefixed with "On" as a naming convention. In ASP.NET markup, you use the attribute OnClick but what you're really doing is wiring a method to the "Click" event. Therefore, the method autogenerated for you by VS is ButtonName_Click. This method is internally passed as a delegate to the event itself.