Link to home
Create AccountLog in
Avatar of baffledbill
baffledbillFlag for Canada

asked on

VB.NET best practice for where to set initial values on a form

When coding initializations in a Windows form, does it matter whether it's done in the New sub or in the Load event?

For example, when initializing a form I might want to:
- set Me.Text to the application's name and version
- capture the user's name
- create collections of objects for use later in the code
- load settings from a file or database to load into combo boxes or other objects
etc etc

Is it better to do these sorts of things in New or in Load? Or are some things better done in one than the other?
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
The place to do that sort of thing is in a separate subroutine that can then be called from either New or Load as Eric suggests.

Keeping it in a separate subroutine called eg InitialiseDefaults() will also mean that you can call it again within your code if you need to reset the form
Avatar of baffledbill


Thanks Eric and ChloesDad. I do create initialization subroutines when they need to be repeated or called from different moments of the process, such as form reactivation or some other trigger. Even so, I don't think this addresses the question of whether the first initialization would be best called from the form's constructor or its Load event.

Eric, from what you're saying it sounds like the main thing to consider would be the type of object, i.e. whether it's a form object as opposed to a variable, due to availability. Am I understanding your comment correctly?
>>Am I understanding your comment correctly?

Yes. Variables and properties can be initialized in the constructor without a problem. Controls are better from the Load event.
That makes sense. Thanks very much for your help.
As long as InitializeComponents is called in the constructor, the controls should be available. The only comment I would make is that there's a small chance that your initialization could break if someone inadvertently detaches the Form_Load handler from the form. You can't disassociate a constructor, so it will always run. If the handler isn't attached, then your handler won't run. Food for thought.
I have some 3rd party controls that are not "available" even after the InitializeComponents has been called. Apparently, they postpone initialization until the control is really used (when made visible). You often see this behavior when controls are hosted in a hidden container like a tab control.