Whats the difference between a form constructor and the form_Load method?
Whats your though process for placing items in one vs the other?
Whats the difference between a form constructor and the form_Load method?
Whats your though process for placing items in one vs the other?
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.
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.