Opening forms using C#. Is one way better than another?

rwheeler23
rwheeler23 used Ask the Experts™
on
What is the difference between opening a form this way:


if (ViewGLDistributionsForm == null)
{
    ViewGLDistributionsForm = new frmViewGLDistributions();
}
else
{
    if (ViewGLDistributionsForm.Created == false)
    {
        ViewGLDistributionsForm = new frmViewGLDistributions();
    }

}

ViewGLDistributionsForm.Show();
ViewGLDistributionsForm.Activate();

Open in new window



...and opening it this way?

using (frmLookupBatchIDs LookupBatchIDsForm = new frmLookupBatchIDs(batchNumber))
{
    if (LookupBatchIDsForm.ShowDialog(this) == DialogResult.OK)
    {
        LookupBatchIDsForm.Show();
        LookupBatchIDsForm.Activate();
        LookupBatchIDsForm.Focus();
        batchNumber = LookupBatchIDsForm.CellValue;
    }
}

Open in new window



I am still learning C# and I see multiple ways to open forms. Is there a proper way or is one way better under one set of circumstances and another way better under another set of circumstances?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
I'll simplify this down to just ShowDialog() or Show().

You use ShowDialog() to display the form as modal, which means that the user is locked into responding to that form until it closes. If the user tries to access a different form or window in the app, it won't let them.

Show() is the opposite - it displays the form as non-modal, which means it's just another window in your app and users can switch to the other open forms/windows in your app.

You typically use modal (ShowDialog) when it's important that the user respond to something your app is asking, like, "Are you sure you want to delete this?" - when you want the user's full focus.

The non-modal forms are usually the ones that users are normally working in and keep open for long periods of time.
AndyAinscowFreelance programmer / Consultant
Commented:
Or are you talking about the using keyword?  The using keyword helps in disposal of the form (or other object) should there be an error such as an exception.  The disposal occurs when the using code block exits.  It also means the object created is local to the scope of the using block.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial