coding coding - 22 days ago 6
C# Question

Initialize windows form object dynamically

How can I dynamically initialize a win form. In my application I am having numerous forms, like more than 50 and the below code is repeated as many times..

so I want to create some function for it and do this job. But how can I create a

new () instance
of a particular Form.

Any help will be greatly appreciated.

private void ShowForm(object frm)
{
if (frm == null || frm.IsDisposed)
{
frm = new <<Here is some Class Name>> { MdiParent = this };
frm.Show();
frm.WindowState = FormWindowState.Maximized;
}
else
{
frm.Activate();
}
}

Answer

If you know the Type to use, you can use Activator.CreateInstance:

private void ShowForm(Form form, Type type)
{
    if (form == null || form.IsDisposed)
    {
        form = (Form) Activator.CreateInstance(type);
        form.MdiParent = this;
        form.Show();
        form.WindowState = FormWindowState.Maximized;
    }
    else
    {
        form.Activate();
    }
}

Or if you're calling it from different places and know at compile-time which type to use:

private void ShowForm<T>(T form) where T : Form, new()
{
    if (form == null || form.IsDisposed)
    {
        form = new T();
        form.MdiParent = this;
        form.Show();
        form.WindowState = FormWindowState.Maximized;
    }
    else
    {
        form.Activate();
    }
}