I'm writing WinForm app where every new form is child form of main form. Every time I call menustripitem click I use such code:
bool opened = false;
foreach (Form forma in Application.OpenForms)
{
if (forma is frm_formname)
{
opened = true;
break;
}
}
if (!opened)
{
frm_formname frm = new frm_formname();
frm.MdiParent = this;
frm.Show();
}
else
{
MessageBox.Show("Form already exist");
}
How can I change the code to make a method from this code where I will pass formname and mainformname as parameter and on click event call this method sending this 2 parameters not the whole code?
You can't use a string, you should pass the type of the form you're looking for as a parameter. Something like this should work (untested!).
public void FindOrCreateForm(Type formType)
{
bool opened = false;
foreach (Form forma in Application.OpenForms)
{
if (forma.GetType() == formType)
{
opened = true;
break;
}
}
if (!opened)
{
Form frm = (Form) Activator.CreateInstance(formType);
frm.MdiParent = this;
frm.Show();
}
else
{
MessageBox.Show("Form already exist");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.