ASP.NET developers typically handle a Page object’s Load event with a Page_Load event handler. In 1.x the designer generates code inside an InitializeComponent method to explicitly wire Page_Load to the Load event.
Lately, I’ve seen more than a handful of people dropping the Page_Load event handler in favor of overriding the Page OnLoad method. This appears to be happening more and more in 2.0, for a few reasons.
First, for C# developers using a separate CodeFile, it’s not immediately obvious how to add any Page event handler if the event is not already present. Unlike the VB editor, there are no drop down controls available to add an event, and intellisense offers no assistance. The method signature has to exactly match what ASP.NET will be looking for, because C# webforms use AutoEventWireup=”true”. Ironically, VB webforms use AutoEventWireup=”False” because the Handles keyword allows a VB developer to wire up an event in place.
Secondly, there is a small performance benefit in not creating a delegate (with reflection no less) and having the garbage collector clean up the same delegate afterwards.
I’ve been thinking about the OnLoad approach, and I even posted code in a recent entry using OnLoad instead of Page_Load. I’m not comfortable enough to make the switch, however. The purpose of OnLoad is to raise a Load event. Overriding a virtual method implies I want to change that behavior, which isn’t precisely true – I just want to setup the webform and get ready for databinding, etc. There is also a comfortable consistency in handling all Page and control events using event handlers of the form VariableName_EventName. Finally, if someone forgets to forward the OnLoad call to the base class, frameworks will break easily.
P.S. To add Page event handlers in C# code easily, use inline code instead of a separate code file. The ASPX editor provides the drop down controls to select Page events when in source view. Drag and drop, baby. It’s the future.