What setup code should go in Form Constructors versus Form Load event?
Asked Answered
K

2

62

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?

Klipspringer answered 26/3, 2010 at 5:43 Comment(3)
A third possibility is the Shown event. I've found that some things like "this.Activate();", "this.BringToFront();" and "this.Focus();" have a better chance of working there than in the FormLoad event.Admix
Possible duplicate of Winforms Form Constructor vs Load eventOrchestrate
see also #3671306Sigma
B
86

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 .NET way is to initialize class objects in the constructor, there are very few compelling reason to not do so for the Form class.

The Load event runs right after the window handle for the form was created, just before it becomes visible to the user. You should only write code in the event handler that depends on having the handle created. There is not a lot of code that qualifies for this requirement except one kind: code that requires the window 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. Once the native control gets created, Winforms initializes it with a bulk update instead of one node/item at a time as will happen when the code runs in the Load event. Big difference.

Last but not least: you should never use the Load event, you should override the OnLoad() method. This ensures code runs in a predictable order when you (or somebody else) inherits from your Form class. IntelliSense helps you write this method, just type "protected onl" and press tab to have IntelliSense auto-complete the method. Note how you have a choice to put code before or after the base.OnLoad() call, that's how you control who is the boss. You are the boss when you put it after, not often the correct choice btw.

Bosomed answered 26/3, 2010 at 11:51 Comment(3)
Excellent info thanks - but on the last point why does Microsoft give us the load event to easily use in VS if one should be really overriding OnLoad anywayKlipspringer
To encourage programmers to move to .NET 8 years ago, that was the familiar programming model. Overriding OnLoad is really easy too, IntelliSense does 80% of the job when you start typing. But it takes typing instead of clicking. Unfortunately, "easy to use" doesn't always mean "correct to use".Bosomed
It's good to know that (unlike some other frameworks I've used) in Winforms you can initialise controls in the constructor. Works a treat.Repository
M
10

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().

Missing answered 26/3, 2010 at 6:5 Comment(3)
@astander: can you say what this text means by "initialization"? For instance, does it mean loading data from a database for displaying in form controls?Fitzgerald
I would say yes, and initialization of controls, classes etc, as can be seen from the InitializeComponent(); call in standard forms. As mentioned here, be carefull of long running initializations, that might rather be called when needed by the user and displaying a Please wait or somehing to the like...Missing
"For this reason Microsoft recommends that you handle initialization code in the Forms Constructor" - it would be nice to have a source for this recommendation.Mukul

© 2022 - 2024 — McMap. All rights reserved.