How to check if window is opened and close it
I am working on C# winforms.
I have function Validate()
which is present in the CS file. When I call function Validate()
it opens ErrorForm using
ErrorForm ew = new ErrorForm(Errors); // Errors is list<string>
ew.Show();
But when I call it again, a new window opens and my previous window is open too. I have to close that window manually.
Is there any method available such that if I call valid开发者_Python百科ate()
again, it will close the current ErrorForm
and will open new ErrorForm
.
try this one:
var f1=Application.OpenForms["ErrorForm"];
if(f1!=null)
f1.Close();
f1= new ErrorForm(Errors);
f1.Show();
Try something like this, a pseudocode..
public class MyClass
{
ErrorForm ew = null;
public void Validate()
{
if(ew !=null && !ew.IsDisposed)
ew.Close();
ew = new ErrorForm(Errors);
ew.Show();
}
}
Simplest solution is calling ew.ShowDialog(this)
which keeps the ErrorForm on top of your main form.
If you really want to call Form.Show()
method, you could implement Singleton pattern in ErrorForm and call GetInstance. In the GetInstance method you can close it or reuse it.
public class ErrorForm
{
private static ErrorForm instance;
private ErrorForm() {}
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new ErrorForm();
}
else //OR Reuse it
{
instance.Close();
instance = new ErrorForm();
}
return instance;
}
public Errors ErrorMessages
{
set {...}
}
}
In the validate method
public void Validate()
{
ErrorForm ef = ErrorForm.GetInstance();
ef.ErrorMessages = errors;
ef.Show();
}
You may use following collection accessible as static property:
Application.OpenForms
you can use the ShowDialog()
精彩评论