Click here to Skip to main content
15,667,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends,

may anyone can help me.
I am looking for a solution to open a dialog: by using a string that contains the name to make it more flexible.
I tried with Type.GetType("xyz"), but it works only without the additional parameter (this).

Many thanks in advance.
KM Perumal 2-May-13 1:01am    
DO you want Pass string value one form to another form is it??

1 solution

Try following code:
private void LoadNewForm(string formName)
Assembly assembly = Assembly.GetExecutingAssembly();
Form myForm = assembly.CreateInstance(formName) as Form;

[updates based on SA's suggestion]
Note that this will try to instantiate the form from the current assembly, which might not be the case. If you want to make some plugin feature (and you don't want to use standard plugin frameworks like MEF or MAF[^] for some reason), you can also load assembly at runtime. Please see: Using Reflection to load unreferenced assemblies at runtime in C#[^].

This works too, and you do not need to know the assembly.
private void LoadNewForm(string formName)
Type t = Type.GetType(formName);
Form frm = Activator.CreateInstance(t) as Form;

You have to pass the fully qualified name of the form type in both cases.
It is an other topic if you want to grab an existing instance of the form.
Share this answer
Sergey Alexandrovich Kryukov 1-May-13 17:28pm    
I voted 4. The whole idea of initializing anything by name is bad. I could only be used for initializing anything from persistent storage. Imaging what happens if you rename the form type. (You also should have indicated that OP should use form type name, not form name (property "Name")). Now, nothing guarantees than the calling code is in the same assembly as the form type. At least it should be mentioned. And the third big sin: exception handling it too local. If you simply omitted exception handling, the code sample would be millions times better.

Thank you for understanding.
Zoltán Zörgő 2-May-13 1:31am    
I never said it was the perfect solution for an unknown situation...
Sergey Alexandrovich Kryukov 2-May-13 1:33am    
Agree. Still, some of my notes are still valid; the last one — for certain.
Zoltán Zörgő 2-May-13 3:38am    
For sure. See update.
Sergey Alexandrovich Kryukov 2-May-13 9:10am    

A note for OP: The idea is vague; but it does not look like it is a way to improve flexibility. Most likely, we could provide much better advice if we knew the ultimate goals of the project and the issues to be addressed.


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