I am using .NET Windows Forms. My MDI parent form contains the menu. If click the menu the form will be displayed. Up to now no problem.
UserForm uf = new UserForm();
uf.Show();
uf.MdiParent = this;
If I click the menu again another duplicate of the form is created. How to solve this issue?
You could just examine the MdiChildren property of your host form to determine if an instance of your UserForm exists in it.
This will create a new instance of your UserForm is it doesn't already exist, and it will switch to the created instance if it does exist.
In contrast to the existing answers here, I would not recommend using a Singleton for this. The Singleton pattern is woefully overused, and is generally a "code smell" that indicates that something's gone wrong with your overall design. Singletons are generally put in the same "bucket" as global variables: you'd better have a really strong case for using it.
The simplest solution is to make an instance variable on your main form that represents the form in question, then use that to show it.
Options:
UserForm
a singleton: http://msdn.microsoft.com/en-us/library/ff650316.aspxmenuItem.Enabled = false;
Typically, disabling the button works fine, and makes more sense from the user's perspective. Singleton works if you need the button enabled for something else.
Singleton is probably not a good solution if the form could be closed and a new instance will later be required.
If you know the name of the form :
You could always make the Form a Singleton:
Then your call would look something like:
You should create a
singletonclass for managing your form instances:NB, this is a very simple Singleton pattern. For the correct way to use the pattern, use this link.You can then just access the form as follows:
When
FormProvider.UserForm
is accessed for the FIRST time, it will be created. Any subsequent get on theFormProvider.UserForm
property will return the form that was created on first access. This means that the form will only ever be created once.