[Solved] C# Method makes forms dynamically via string


Here’s a simple example using the Reflection approach:

private void button1_Click(object sender, EventArgs e)
{
    Form f2 = TryGetFormByName("Form2");
    if (f2 != null)
    {
        f2.Show();
    }
}

public Form TryGetFormByName(string formName)
{
    var formType = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
        .Where(T => (T.BaseType == typeof(Form)) && (T.Name == formName))
        .FirstOrDefault();
    return formType == null ? null : (Form)Activator.CreateInstance(formType);
}

Here’s an alternate version that checks to see if the form is already open:

public Form TryGetFormByName(string formName)
{
    // See if it's already open:
    foreach (Form frm in Application.OpenForms)
    {
        if (frm.Name == formName)
        {
            return frm;
        }
    }

    // It's not, so attempt to create one:
    var formType = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
        .Where(T => (T.BaseType == typeof(Form)) && (T.Name == formName))
        .FirstOrDefault();
    return formType == null ? null : (Form)Activator.CreateInstance(formType);
}

solved C# Method makes forms dynamically via string