Reflection: Displaying a Form By Name

Posted Fri, Jul 3 2009 9:20 by Deborah Kurata

There may be situations when you want to display a form by its form name. For example, say that you retain your menu options in a database so they can be customized. You want to associated a menu option with the display of a particular form. So you store the form name in the table.

But then you need a way to show that form at runtime. For this, you need reflection.

In VB:

Dim formName as string = "CustomerForm"
Dim assemblyName As String = My.Application.Info.AssemblyName
Dim componentName As String = assemblyName & "." & formName
Dim type As Type = type.GetType(componentName, False, True)
Dim form As Form = TryCast(Activator.CreateInstance(type), Form)
form.ShowDialog()

In C#:

string formName = "CustomerForm";
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
string componentName  = assemblyName + "." + formName;
Type type = Type.GetType(componentName, false, true);
Form form = (Form)Activator.CreateInstance(type);
form.ShowDialog();

This code first determines the component name by appending the assembly name and form name. This code assumes that the form is in the current assembly. If that is not the case, you could instead store the assembly name in the table and use it in the above code.

The code then gets the appropriate type for the component and uses CreateInstance to create an instance of that type.

Enjoy!

Filed under: , , ,

Comments

# re: Reflection: Displaying a Form By Name

Thursday, September 24, 2009 1:35 PM by Jim Kahl

This works great as long as you are calling a form that resides inside the assembly.  I need to be able to display a form that resides in another assembly.  I have tried many samples on the internet and find that they do not work and either give me a null reference exception as soon as I try frm.Show or when I try to invoke the Show method as (obj.GetMethod("Show").Invoke(inst, Nothing)) it gives an ambiguous name exception.  How can I perform this?

Leave a Comment

(required) 
(required) 
(optional)
(required)