views:

334

answers:

3

Hi,

What is the difference between OnLoad method and Load event? I am developing WinForm controls. Should I register to Load event or override the OnLoad method? What are the advantages and the disadvantages of each one?

Thank you.

A: 

OnLoad is the default event handler used in VB.NET to handle the Load event. I typically override this method when I need to attach code to the load event. There are also default functions for the other Page Life Cycle events: OnPreRender, OnInit, etc.

regex
Oops... Just realized you were asking about winform. Disreguard page life cycle link. Same applies though.
regex
+5  A: 

I'd go for overriding OnLoad, so you spare the CPU cycles to invoke the event handler.

The general pattern is to override a method, if you inherit from a control; otherwise, subscribe to the event.

But remember to call the base class' OnLoad method, because that's where the Load event invoked.

Thomas Freudenberg
According to Microsoft, overloading the OnLoad method is the '.. preferred technique for handling the event in a **derived** class' (see http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onload.aspx)
Troy Moon
+2  A: 

OnLoad method is the one that raises Load event. It's a standard pattern in framework classes, and a generally recommended one - for any event Foo, you have a virtual protected method OnFoo which raises that event; and no other method of the class raises the event directly, but always calls OnFoo.

If you need to handle the event on this, it's usually both easier and faster to override OnFoo.

Pavel Minaev