I would like someone to try and explain the difference between these. More specifically, example usage scenario\'s.
I am refactoring some Windows Form
OnLoad
raises the Load event, which Form_Load
handles. See the MSDN article.
So, in your code, at the end of your initialization function, you could call the OnLoad
function. The base class will then call your event handlers (Form_Load
in this case), which you may have set in your initialization code.
Personally, I would place my code in the Form_Init
and leave OnLoad
for initiating the event, since I'm handling the event, although you can defend either with good reason, as you see from your answers.
You should always override OnLoad(). Using the event is only appropriate when another class would be interested in the event. Which is what events are for. Another class being interested in the Load event is very rare, only really useful to do window arrangement stuff.
Still, the Load event works well with the designer and VB6 programmers are very comfortable with it. It isn't horribly wrong, you'd only get in trouble when you start inheriting the form and code doesn't run in the right order.
Most code that now gets put in the Load event really belongs in the constructor. You only need OnLoad if:
When overriding OnLoad
, the call to base.OnLoad
invokes the Load
-event of the Form.
protected override void OnLoad(EventArgs e)
{
// do stuff before Load-event is raised
base.OnLoad(e);
// do stuff after Load-event was raised
}
If you don't specifically need to perform stuff before the Load-event is raised, placing the code in OnLoad
after base.OnLoad(e)
gives the same runtime behaviour as placing it in the Form_Load
event handler.
I would recommend overriding the method rather than subscribing to the event.