Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should the Form.Load event be used compared to its constructor method?

Tags:

c#

.net

winforms

When initializing properties of controls or other values related to a Form I have a tendency to switch back and forth between initializing the values in the Form's constructor and then later when the Form.Load event is evoked.

What is the generally accepted usage of a Forms constructor vs it's Form.Load event? With other classes I would do all initialization in the constructor. Yet in in VS when you double click on a Form it jumps you to an event handler for the Form.Load event not the constructor. This leads me to believe that it's preferable to do all the initialization after the Load event instead of the constructor.

like image 367
Eric Anastas Avatar asked Jul 07 '10 22:07

Eric Anastas


1 Answers

Yes, it is a wee bit sad that it works that way. It made a lot of sense at the time, now 10 years ago already. Windows Forms was targeted to be a replacement for VB6, the dominant point-and-click UI designer at the time. And Form_Load was important in VB6, that's where you customized the form view.

That wasn't really appropriate from the get-go, the Form class has a true-blooded constructor. And you can set control properties in the constructor before the actual native Window control gets created. There's a ton of code in WF to make that work. Code that the designer relies on, it sets these properties before the Load event fires. It is very efficient to do so, many controls get a lot slower when they need to be updated after their window is created. Like ListView and TreeView.

There are few reasons to not use the constructor yourself, like the designer does, especially since the C# IDE doesn't try to hide the constructor. Except one: you need the Load event when you write the kind of code that requires knowing the actual form size. That size isn't known until the window actually gets created, the Load event is the earliest after that. That ought to be rare.

And of course, if you do want to use Load then you override OnLoad instead of using the Load event. That would be another one.

like image 189
Hans Passant Avatar answered Oct 21 '22 04:10

Hans Passant