Which is a better way to show a modal dialog?
form1 frm=new form1();
frm.showDialog()
or
(new form1()).showDialog();
Neither one is "better" than the other; they are perfectly equivalent!
However, in this particular case, both are wrong. The ShowDialog
method requires you to call the Dispose
method on the form. Unlike the Show
and Close
combination, this is not done automatically. From MSDN:
When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to
DialogResult.Cancel
. Unlike non-modal forms, theClose
method is not called by the .NET Framework when the user clicks the close form button of a dialog box or sets the value of theDialogResult
property. Instead the form is hidden and can be shown again without creating a new instance of the dialog box. Because a form displayed as a dialog box is hidden instead of closed, you must call theDispose
method of the form when the form is no longer needed by your application.
Thus, you should choose between one of these (equivalent) forms:
using (Form1 frm = new Form1())
{
frm.ShowDialog();
}
or
Form1 frm = new Form1();
frm.ShowDialog();
frm.Dispose();
The reason that ShowDialog
doesn't automatically dispose the form is simple enough, if not immediately obvious. It turns out that applications often wish to read values from an instance of a modal dialog form after the form has been closed, such as settings specified in the form's controls. If the form were automatically disposed, you would be unable to read those values by accessing properties of the form object. Thus, the programmer is responsible for disposing forms shown as modal dialogs when (s)he is finished with them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With