views:

207

answers:

3

Whats the difference between a form constructor and the form_Load method?

Whats your though process for placing items in one vs the other?

+2  A: 

Look here: http://bytes.com/topic/c-sharp/answers/549118-load-event-vs-constructor

Paja
Interesting thread, but the OP appears to have come to the wrong conclusion. With the exception of code required to initialize the form and it's controls, I generally don't put things like database initializations (or anything else for that matter) in the constructor of the form, as that too tightly couples those operations to my form. The constructor is supposed to "construct" the form, and nothing else. Form events are provided so that work unrelated to constructing the form can be performed.
Robert Harvey
He said he do not do any DB interop in ctor Ctor code should be as short as possible. He creates a thread that do the DB interop.
Paja
@Paja: I think I misread the thread. You're right, he's using the Load event to execute this code. +1
Robert Harvey
+2  A: 

Code in the constructor runs immediately when you create the form, whether or not you ever display it. Code running in the Form.Load event is an event handler, so you can actually have code in other classes (which have subscribed to the form) run code there. Similarly, you can (from the form) use the Form.OnLoad method to run code.

The form's Load event (and OnLoad overridable method, which is often a better choice in the form itself) runs after the form has been initialized. This often has advantages, since all of the form's controls have already been constructed, and more importantly, all of the form layout has occurred.

Reed Copsey
+1  A: 

Don't use the Load event, override the OnLoad() method. That ensures that everything runs in a predictable order when you derive from the form class. You should only use it for form initialization that requires the size of the actual form to be know. It can be different from the design size due to scaling or user preferences and the actual size isn't know until the native window is created.

Initializing controls in the OnLoad method is possible but it can be very slow, especially for ListView and TreeView. If you initialize them in the constructor, they can be bulk-initialized when their native Windows controls are created.

One special exception: creating an MDI child window should always be done in OnLoad(), there's a bug in the plumbing code that messes up the MDI bar when you create a child in the constructor.

Hans Passant