What Setup Code Should Go in Form Constructors Versus Form Load Event

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

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.

Form constructor vs Form_Load

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.

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

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.

Defferent between constructor and form load?

Well simply put the constructor is called when the class is instantiated like all constructors, while the page load is called whenever a form is displayed for the first time.

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.load(v=vs.110).aspx

Form_Load() 'event' or Override OnLoad()

You should always override OnLoad(). Using the event is only appropriate when another class would be interested in the event. Which is what events are for. Another class being interested in the Load event is very rare, only really useful to do window arrangement stuff.

Still, the Load event works well with the designer and VB6 programmers are very comfortable with it. It isn't horribly wrong, you'd only get in trouble when you start inheriting the form and code doesn't run in the right order.

Most code that now gets put in the Load event really belongs in the constructor. You only need OnLoad if:

  • You need to know the exact size and position of the window. OnLoad is best, the window Handle is created and the user preferences are applied (title and border size) and the form was rescaled as directed by the Form.AutoScaleMode property. The window is not yet visible, a very good time to move the window somewhere else or to arrange the child controls.
  • You have code that needs the Handle property. This is subtle, you cannot always tell. Having code like that in the constructor is unhealthy, the window gets created before the constructor completed. It usually comes to a good end but it can make creating the form very slow. Easy to diagnose from the Call Stack window.
  • To avoid a bug in the MDI implementation. If you create an MDI child in the parent constructor then you'll get duplicated glyphs, visible when you maximize the child. Create the child in OnLoad instead.

c# what gets executed first the constructor or the onLoad?

The constructor - Form1_load is an instance method which requires a valid instance in order to be called.

Where to put On Load code for C# Forms

You should initialize class elements as early as practical. For most things, that will be in the constructor. You can initialize control properties, class fields, etc. here and it will work fine.

However, there are some things you cannot do with a Control instance (including a Form subclass) until the underlying native window handle has been created. For these types of initialization, overriding OnLoad() (or handling the Load event) and performing that initialization (only) is appropriate.

As an example, when I am showing a form to display progress for a background task, I will handle the Shown or Load event (for this purpose, they are equivalent) and not start the background task until then. This ensures against the background task finishing so quickly that the form hasn't even been fully initialized by the time it's done, which would prevent the post-task code from closing the form (you can't close a form that hasn't been opened yet :) ).



Related Topics



Leave a reply



Submit