When you create a new web user control in visual studio it by default adds the Page_Load event. What is the advantage to using this rather than overriding the base OnLoad
event on the control? Is it just that the Page_Load
event fires before OnLoad
?
views:
1785answers:
7The OnLoad
method should be the place where the Load
event is raised. I personally always try to handle the event unless I need to do extra processing around raising the event.
I recommend handling the event itself under normal circumstances.
You may find this article on the page lifecycle from Microsoft useful.
Even though you're inheriting from UserControl
, I think you should stay away from overriding the protected methods if you don't have to. The Page_Load
is there to make it easier for you to add the code that's specific to your UserControl
.
Only override OnLoad
if you need absolute control over when(/if) the Load
event is fired (which should be rare, IMO).
It's really just a matter of choice. To me it seems weird for an object to attach an event to itself, especially when there is a method you can override.
I think the ASP.NET team used events because that was the model for Global.asa in ASP, and to lower the bar for developers who don't understand inheritance and overriding virtual methods.
Overriding the method does require more knowledge about the page lifecycle, but there is nothing "wrong" with it.
As you can see above, it does mostly come down to personal choice IF that choice is made knowledgeably. The best quick but solid overview I've seen is at http://weblogs.asp.net/infinitiesloop/archive/2008/03/24/onload-vs-page-load-vs-load-event.aspx
i think it's the same. IMHO, With Events, you have a bit of more flexibility, because you can happen more than one listener to your event!
I think there is one potentially significant difference in the two methods.
What I am referring to is the ability to have control over the execution sequence.
If you are overriding, you know when the base classes Load will take place because you are calling it. This provides more control, but probably is a bad thing as many will argue.
If you use event, you have no guarantee in terms of order of call. This forces you to write Load event which should be agnostic about what super classes are doing during Load phase. I think this would be the preferred approach and maybe that is why VS auto-generated code is this way.