简体   繁体   中英

To Form Load() or Not to Form Load()

Should I load child forms in the Constructor or the FormLoad()?

I have some code that is calling a custom class that embeds a form in a control. I had originally been declaring my child forms outside the Constructor and then calling a FormPaint() routine in the FormLoad() to then load the forms like so:

internal frmWWCMCPHost frmWWCMCPHost = new frmWWCMCPHost();
internal frmWWCEnrollmentHost frmWWCEnrollmentHost = new frmWWCEnrollmentHost();
internal frmWWCMemberHost frmWWCMemberHost = new frmWWCMemberHost();

public frmWWCModuleHost()
{
    InitializeComponent();        
}

private void frmWWCModuleHost_Load(object sender, EventArgs e)
{
    FormPaint();
}

public void FormPaint()
{
    WinFormCustomHandling.ShowFormInControl(frmWWCMCPHost, ref tpgMCP, FormBorderStyle.FixedToolWindow,-4,-2);
    WinFormCustomHandling.ShowFormInControl(frmWWCMemberHost, ref tpgMember, FormBorderStyle.FixedToolWindow, -4, -2);
    WinFormCustomHandling.ShowFormInControl(frmWWCEnrollmentHost, ref tpgEnrollment, FormBorderStyle.FixedToolWindow, -4, -2);

    // Call each top-Level (visible) tabpage's form FormPaint()
    frmWWCMCPHost.FormPaint();
}

Now I have been shown a much better way of embedding forms in container controls, as it relates to my custom class, here .

My question is where should I be loading these as the example has them being loaded in the Constructor declaring them at the same time, like so:

public frmWWCModuleHost()
{
    InitializeComponent();
    WinFormCustomHandling.ShowFormInContainerControl(tpgCaseNotes, new XfrmTest());
}

Which is, obviously, much less code. By loading in the constructor will I be using far more unnecessary resources? Will I be gaining anything? How do I decide?

I prefer to use form's constructor. I mean setup everything before a form would be shown, not after.

降低向外复杂性将提高可读性并减少可能的错误。

On a tangent, never ever rethrow an exception using throw ex; It'll reset the call stack. Just use throw;

Interesting question Mr_Mom. My recommendation would be to use your constructors to do only the setup needed for the sub forms and put off loading the sub forms until the parent formLoad().

As for resources, gains, and losts... I do not know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM