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?
相关问题
- Generic Generics in Managed C++
- thread_local variables initialization
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
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();
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.
A call to InitializeComponent is automatically inserted in the constructor of your form/page. InitializeComponent is the auto-generated method that
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.