For winforms applications I'm wondering what setup code should go in:
- MainForm()
as opposed to
- MainForm_Load(object sender, EventArgs e)
Are there any best practice guidelines here?
For winforms applications I'm wondering what setup code should go in:
as opposed to
Are there any best practice guidelines here?
Have a quick look at Use Constructor in Windows Forms to Ensure Proper Initialization
Use the Constructor in a Windows Form for ensuring that initialization is done properly. Event firing order is not an exact science, and you cannot always depend on the order in which events fire, regardless of what you have seen in the past.
....
For this reason Microsoft recommends that you handle initialization code in the Forms Constructor, assuming that you do not have a really time-comsuming initialization that could get time-sliced or do a DoEvents().
Programmers that have worked with VB6 tend to put a lot of code in the Load event, in VB6 that event was used to initialize the form. But that's not appropriate anymore in Windows Forms, the Form class can have a constructor.
The Load event runs right after the window handle for the form was created, right before it becomes visible. You should only write code in the event handler that depends on having the handle created. There is not a load of code that qualifies for this requirement except one kind: code that requires the form size and location to be known.
The design-time Size and Location property values of a Form are not the same as their actual values when the form runs on another machine. The form can get rescaled to accommodate the system font size or the video adapter DPI setting on the target machine. The user preferences play a role too, the user might have selected a different font size for the window caption. You don't typically care about any of this, unless you want the window to have a particular position on the desktop or be aligned with some other window.
Writing code in the Load event that does things like initialize TreeView or ListView controls can actually dramatically slow down the startup time. When you do it in the constructor, Windows Forms doesn't have to update the physical window yet, it hasn't been created yet.
Last but not least: you should never use the Load event, you should override the OnLoad() method. This ensures it works properly when you (or somebody else) inherits from your Form class.