I am using this function to close existing form and open a new form.
If there is no exixting form, it throws error.
Error :
Target : System.Object
If you know the name of the form you can as well do like this :
var frm = Application.OpenForms.Cast<Form>().Where(x => x.Name == "MyForm").FirstOrDefault();
if (null != frm)
{
frm.Close();
frm = null;
}
if (ApplicationFormStatus.CheckIfFormIsOpen("FormName"))
{
// It means it exists, so close the form
}
public bool CheckIfFormIsOpen(string formname)
{
//FormCollection fc = Application.OpenForms;
//foreach (Form frm in fc)
//{
// if (frm.Name == formname)
// {
// return true;
// }
//}
//return false;
bool formOpen= Application.OpenForms.Cast<Form>().Any(form => form.Name == formname);
return formOpen;
}
I have pasted the two methods one simple one and the second one is the LINQ.
You can use the Application.OpenForms collection.
this part of code searches for existing instance of a form if exists just shows it , and if not creates an instance of it
`foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(myMainform))
{
form.Activate();
form.Show();
this.Close();
return;
}
}
myMainform m = new myMainform();
m.Show();`