tags:

views:

525

answers:

3

When a form loads, the code needs to do things like setup datagrids, combo boxes, set the title etc. I've tended to always use the load event rather then the new. Is there any guildlines for which one is best for which activities?

+1  A: 

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.

Ty
A: 

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.

Gishu
+1  A: 

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

Calanus