Instantiate/Show Form From String (where the string contains name of the form class)

M

Merk

I'm wanting to know if/how it would be possible to load a form based on a
string that contains the name of the form (class).

For example, instead of doing this:

myForm f = new myForm();
f.Show();


I would like to load the form when its class name is in a string variable
like this:

string formClassName = "myForm"
?? what goes here to instantiate/load the form based on the value of
formClassName?

Thanks!
 
D

Dave Sexton

Hi,

Form form = (Form) Activator.CreateInstance(Type.GetType(formClassName));

formClassName must contain the namespace of the form Type, such as
"SomeNamespace.YourForm". Also, the Form that you're trying to instantiate
must exist inside the assembly from which the line above is being called,
otherwise the formClassName string must contain an AssemblyQualifiedName,
such as "SomeNamespace.YourForm, YourAssembly".

If you don't know the namespace use:

System.Reflection.Assembly.GetAssembly(typeof(AKnownTypeInTheAssembly)).GetTypes()

and iterate the Type array, comparing the Name property of each type to your
formClassName (although if there are two classes with the same exact name in
different namespaces, your code will just take the first one it sees)

If you don't even know of any Type in the assembly before design time,
you'll have to use one of the other static methods on the Assembly class to
load the appropriate assembly, such as GetExecutingAssembly, for example.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top