Winforms Form Constructor vs Load event
Asked Answered
M

3

14

When a form loads, the code needs to do things like setup datagrids, comboboxes, set the title, etc. I've tended to always use the load event rather than the new (constructor). Are there any guidelines for which one is best for which activities?

Mehala answered 5/11, 2008 at 5:25 Comment(0)
N
4

A call to InitializeComponent is automatically inserted in the constructor of your form/page. InitializeComponent is the auto-generated method that

  • creates the various UI elements on your winform / XAML page
  • initializes their properties with the values stored in the resource file

So anything related to UI arrangement/modifications should go after this call. When you do this in an override of Form.OnLoad , you're assured that the UI is ready to go (InitializeComponent has been called)... so I'd vote for sticking to OnLoad for UI.
Creating non-UI members, constructor would be the place I'd first look at.

Nerissa answered 5/11, 2008 at 6:38 Comment(0)
M
3

Bear in mind that anything in the constructor of a form will be created/executed at that forms creation. i.e. at:

Form frm = new Form();

Whereas anything in the Load event will occur only when the form is shown i.e. frm.Show();

Manometer answered 5/11, 2008 at 9:46 Comment(1)
Note that there's also a Shown event. The load event occurs before the form is shown but when the window exists and the layout has been done.Sheridansherie
A
2

Basically you want your constructor to be as light-weight as possible. I try to put most things in the Load event handler as the UI elements have been created and are usable at this time. However, I usually instantiate class objects etc. in the constructor as it is actually part of constructing the object. Sometimes you can't put things in one place or the other but for the times when you can, you should just put them where it seems most appropriate.

Arte answered 5/11, 2008 at 5:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.