Using Reflection to open a form by name

Here is a quick example of how the System.Reflection namespace can be utilised to open form instances in a method that accepts the form name as a string. It also shows how you can pass across variables to forms with overloaded constructors.

It’s particularly useful when working with a main menu structure, such as I have in a current project loaded into a Treeview.


private void LoadNewForm(string formName)
{
    try
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        Type type = assembly.GetType(formName);

        //for this form I have an overloaded constructor, accepting a 'User' object
        ConstructorInfo ci = type.GetConstructor(new Type[1] { typeof(User) }); 
        object[] argVals = new object[] { CurrentUser };  //pass 'CurrentUser' variable to form constructor
        Form frm = (Form)ci.Invoke(argVals);

        frm.Show();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
} 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s