Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize windows form object dynamically

Tags:

c#

winforms

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();
    }
 }

2 Answers

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();
    }
}
like image 79
Jon Skeet Avatar answered Dec 02 '25 22:12

Jon Skeet


You can use reflection.

Activator.CreateInstance - MSDN

        frm = (Form)Activator.CreateInstance(t) // t is a type parameter
like image 26
Tilak Avatar answered Dec 02 '25 23:12

Tilak