Ali CAKIL
Ali CAKIL

Reputation: 428

How to call a Widows Form Object over it's name (string)?

Normally we create a form like;

MainForm form1 = new MainForm();
form1.show();

But I want to call this form1 over it's name something like;

string FormName = "MainForm";

// a method should be here that gives us form1 from FormName
// then;

form1.show();

how can I do that? infact, my goal is to show a form by string name which is comming from sql database. Because I have too many windows forms in my project, so I prefer to call forms over sql database

Upvotes: 1

Views: 711

Answers (2)

György Kőszeg
György Kőszeg

Reputation: 18013

Option 1:

If the name is the same as the type name as in your example, you can use reflection:

private static string namespacePrefix = "MyNamespace.";

public static Form CreateFormByName(string formName)
{
    Assembly myAssembly = Assembly.GetExecutingAssembly();
    Type formType = myAssembly.GetType(namespacePrefix + formName);
    if (formType == null)
        throw new ArgumentException("Form type not found");
    return (Form)Activator.CreateInstance(formType);
}

Option 2:

When type names and form names are different, you should use a dictionary mapping:

private static Dictionary<string, Type> mapping = new Dictionary<string, Type>
{
    { "MainForm", typeof(Form1) },
    { "frmOptions", typeof(OptionsForm) },
    // ...
}

public static Form CreateFormByName(string formName)
{
    Type formType;
    if (!mapping.TryGetValue(formName, out formType))
        throw new ArgumentException("Form type not found");
    return (Form)Activator.CreateInstance(formType);
}

Upvotes: 1

rmn36
rmn36

Reputation: 656

This can be achieved through the Type.GetType and Activator.CreateInstance methods. The Activator method will give you a return of type object that represents your newly created object.

string FormName = "MainForm";
Type t = Type.GetType(FormName);
Form f = Activator.CreateInstance(t) as Form;
f.show();

Upvotes: 0

Related Questions