Where should a second form be instantiated?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

having an application with a Main form (Form1) and a second form
(settingsForm1) that should only show up when the user clicks the settings
menu button, where should the code:
settingsForm settingsForm1 = new MyApp.settingsForm()
be placed?

First i have put it inside the Form1.InitializeComponents method thus only
needed to call settingsForm1.show() when the menu button was clicked, but
this lead to the side-effect of the settingsForm showing up in front of the
main form at design time (Form1.cs [design])

Many thanks in advance
 
In this case, you'll want to make a class level variable
for your second form in your main form.

SettingsForm MyForm = null;

Then, create an instance of the form if one
has been created in your method called
from the menu click

private void LaunchSecondForm()
{
if (MyForm!=null) { return; }
MyForm = new SettingsForm();
MyForm.Show();
}
 
Filipe,



You don't have to write any code in InitializeComponents. Only designers are
supposed to write there. If you put your "hand written" code in this method
there are good chances that the code will be removed by VS.



As long as it goes for creating the second form it depends on how you intend
to use the form or to be more precise if the form is a modal dialog box
(shown with Form.ShowModal) or modeless (WindowsForm.Show).



Why is this matter? Because the form behaves differently upon closing.



When modal dialog gets dismissed (closed) the form actually gets only
hidden. The form object stays created and initialized in the memory and can
be re-shown by simply calling ShowModal() again. All fields and stuff will
have their old values. In this case it is safe (and maybe desirable) to
create the form once (e.g. in the main form constructor) and show many times
after that. It could be also the case where you want to create the form
locally in some method, show it and dispose it (it is a good practice to
call form's Dispose method in this case or use C# *using* statement)



On the other hand form shown modeless (Form.Show) gets destroyed as soon as
one closes them. Next time you want to show the form the object needs to be
instantiated again. It makes more sense to keep global references (as
members of the main form class) to the modeless forms, but keep in mind that
when such form is closed the form is disposed, but the object won't be
garbage collected as long as there is reference to it. Therefore if you want
to check whether the reference points to valid form object you need to check
if it is not *null* and of it's not, you need to check its IsDisposed and
Disposing properties in order to decide whether you need to create a new
object or can use the old one.




HTH

Stoitcho Goutsev (100) [C# MVP]
 
Back
Top