问题
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 validate()
again, it will close the current ErrorForm
and will open new ErrorForm
.
回答1:
try this one:
var f1=Application.OpenForms["ErrorForm"];
if(f1!=null)
f1.Close();
f1= new ErrorForm(Errors);
f1.Show();
回答2:
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();
}
}
回答3:
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();
}
回答4:
You may use following collection accessible as static property:
Application.OpenForms
回答5:
you can use the ShowDialog()
来源:https://stackoverflow.com/questions/7240709/how-to-check-if-window-is-opened-and-close-it