Question

I want a method that can only be sent the type of form to open, then open that form.

This is what I have so far:

private void OpenForm(Type t)
{
    if (OpenedForm != null)
    {
        OpenedForm.Close();
    }
        IList list = (IList)Activator.CreateInstance(
        typeof(List<>).MakeGenericType(t));
        OpenedForm.MdiParent = this;
        OpenedForm.Show();
        OpenedForm.WindowState = FormWindowState.Maximized;
}

I know I can make a method like this:

private void OpenForm(Form frm)
{
    if (OpenedForm != null)
    {
       OpenedForm.Close();
    }
    OpenedForm = frm;
    OpenedForm.MdiParent = this;
    OpenedForm.Show();
    OpenedForm.WindowState = FormWindowState.Maximized;
}

And then simply call it like so:

 Form newform = new TestForm();
 OpenForm(newform);

But I would be interested to know if it is possible to do it like I tried in the first code snippet, and what needs to be done to accomplish that.

Was it helpful?

Solution

private void OpenForm(Type t)
{
    if(!typeof(Form).IsAssignableFrom(t))
        throw new ArgumentException("Required description of Form Type", "t");

    if (OpenedForm != null)
       OpenedForm.Dispose(); //will also close a Form

    OpenedForm = (Form)Activator.CreateInstance(t);
    OpenedForm.Show();
    OpenedForm.WindowState = FormWindowState.Maximized;
}

Now you can pass only Type metadata of Form class or it's derived one. So if you do:

OpenForm(typeof(Form));

A new empty form will be created and opened

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top