Reputation: 5299
I have a form that I am showing by a button click. When I click the button the second time, I get a form again. So I want prevent it, that is, I want to show only one form's instance at once. I'd tried to use a singleton:
public partial class MyForm : Form
{
private static Object _mutex = new Object();
private static MyForm _instance = null;
public static MyForm GetInstance(...params...)
{
if (_instance == null)
{
lock (_mutex)
{
if (_instance == null)
{
_instance = new MyForm(..params..);
}
}
}
return _instance;
}
}
And calling it:
private MyForm Form {set;get;}
private void MyButtonClick(object sender, EventArgs e)
{
Form = MyForm.GetInstance(...params...);
if (!Form.Visible)
Form.Show();
}
After the button click, I get a form. After I close it and click the button again, in the result I get an error:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'MyForm'.
What am I doing wrong? Maybe I do not need a singleton, and is there another way to do it?
Upvotes: 0
Views: 1030
Reputation: 851
Use Ispostback
method ..
public partial class MyForm : Form
{
private static Object _mutex = new Object();
private static MyForm _instance = null;
public static MyForm GetInstance(...params...)
{
if (_instance == null)
{
lock (_mutex)
{
if (Ispostback)
{
_instance = new MyForm(..params..);
}
}
}
return _instance;
}
}
Upvotes: 0
Reputation: 411
Wouldn't it be easier to just set a variable that controls if the form is open or not? I do it that way all the time, and whenever I want to do it on multiple windows in one Form I make an array out of it, for example:
if(!isOpen[0]) {
isOpen[0]=true;
Form.Show;
}
For that you make isOpen accessible to the other Forms, then when you close the form in question you set the variable from there back to false with the Closing
event.
Upvotes: 1
Reputation: 12544
The form that is closed, is disposed and cannot be reshown. The instance variable has to be reset to null, or the form has to prevent itself from closing and hiding itself.
e.g.
protected override void OnFormClosed(FormClosedEventArgs e)
{
_instance = null;
base.OnFormClosed(e);
}
Upvotes: 3