Click here to Skip to main content
15,895,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Consider a WinForms project, that defines several Forms; in the Main Form which is launched at run-time is a drop-down containing the names of Forms which have not had an instance created ... yet.

So the drop-down may contain a selection list something like:

TemplateForm1
TemplateForm2
TemplateForm3

At run-time:

1. with Main Form and drop-down visible:

2. The user selects an item from the drop-down. So: now you have a string, containing a name of an object (the Form), like "TemplateForm3."

3. Now you want to create an instance of "TemplateForm3." And, be assured: "TemplateForm3" is the name of a Form that exists in the current Project.

Seems like in the past this type of code used to work for me
var frmType = Activator.CreateInstance(Type.GetType("TemplateForm3"));
But, right now I just get a null exception.

I wonder if I have forgotten some requirement involving either required Reflection on the current assembly here (?), or some other required form of using Activator.CreateInstance and/or some variation on usage of GetType ?

I'd certainly prefer not to use Reflection here.

And, yes, it would be easy to write a switch/case statement, using the string from the drop-down selection to create new instances in the usual way, but I don' wanna :)

Appreciate your help !

thanks, Bill
Posted

1 solution

You have to supply the complete name i.e. "namespace.TemplateForm3".

If you are going to use types which are not in the current running assembly, then yo must supply the fully qualified typename i.e. "namespace.TemplateForm2, filename, Version=..."
 
Share this answer
 
Comments
BillWoodruff 30-Aug-12 7:10am    
Thanks, Mehdi ! I'm surprised I didn't find that "namespace qualification" in the all MSDN docs for Activator.CreateInstance I pored over (yes, I think old age is dissolving the synapses).

best, Bill
Mehdi Gholam 30-Aug-12 7:39am    
Synapses are over rated! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900