Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a form from a string in c#

Tags:

c#

winforms

I have a Windows Application in C# and I need to call a Form whose name is saved into a string variable in run-time.

Like;

I already have the form; Login.cs

string formToCall = "Login"
Show(formToCall)

Is this possible ?

like image 978
Mtok Avatar asked Dec 20 '12 15:12

Mtok


2 Answers

Have a look at Activator.CreateInstance(String, String):

Activator.CreateInstance("Namespace.Forms", "Login");

you can also use the Assembly class (in System.Reflection namespace):

Assembly.GetExecutingAssembly().CreateInstance("Login");
like image 133
Brad Christie Avatar answered Sep 25 '22 15:09

Brad Christie


Using reflection:

//note: this assumes all your forms are located in the namespace "MyForms" in the current assembly.

string formToCall = "Login"
var type = Type.GetType("MyForms." + formtocall);
var form = Activator.CreateInstance(type) as Form;

if (form != null)
   form.Show();
like image 21
Federico Berasategui Avatar answered Sep 23 '22 15:09

Federico Berasategui