I got a code to open my forms without any duplication, but i want to create a method for this, to avoid code redundancy.
My code :
private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Form openForm in Application.OpenForms)
{
if (openForm.GetType() == typeof(form1))
{
openForm.Activate();
return;
}
}
form1 f1 = new form1();
f1.MdiParent = this;
if (!f1.IsDisposed)
f1.Show();
}
What i want to:
public void formOpener(Form form, string formName)
{
foreach (Form openForm in Application.OpenForms)
{
if (openForm.GetType() == typeof(form))
{
openForm.Activate();
return;
}
}
form formName = new form();
formName.MdiParent = this;
if (!formName.IsDisposed)
formName.Show();
}
private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
{
formOpener(form1);
}
I have some issues with the parameters. Thanks for any answer!
Something like that?:
public void formOpener<T>() where T : Form, new()
{
var openedForm = Application.OpenForms.OfType<T>().FirstOrDefault();
if (openedForm != null)
{
openedForm.Activate();
return;
}
T newForm = new T();
newForm.MdiParent = this;
newForm.Show();
}
OfType<T>
extension method requires using System.Linq;
Usage
formOpener<Form1>();
This will show the form if there is any open. Otherwise, will create new one.
If you can have multiple forms of type T open, then use Name
property to distinguish them.
public void formOpener<T>(string formName) where T : Form, new()
{
var openedForm = Application.OpenForms.OfType<T>()
.Where(x => x.Name == formName).FirstOrDefault();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With