cvocvo
cvocvo

Reputation: 1636

Use value of a string to create new form object

I have a main form that is launched and then it can go to any of the other forms I have created. But the kicker is that I have written a class that I call that returns a string with the name of the form to go to.

Currently I don't have this working so I am going from form to form like this (statically written linking code):

this.Hide();
CloudAccess nextForm1 = new CloudAccess(); 
   //Where CloudAccess is the class of the next form.
nextForm1.ShowDialog();

What I want is something like this:

FormController pick = new FormController();
   //Where FormController is the Class I create an object of and ask what's next
string next = pick.whereToGo(); //lets say it returns "CloudAccess"
this.Hide();
next nextForm1 = new next(); //next is desired to be the contents of the string
nextForm1.ShowDialog();

The problem is that I don't know how to use the returned string to make the new object and use it. I've been looking at Invoke and Reflection topics like this one: Use string value to create new instance But I'm new to C# and I'm not sure how to apply that to this scenario.

Thoughts? Thanks!

Upvotes: 2

Views: 5877

Answers (2)

fejesjoco
fejesjoco

Reputation: 11903

Get the type of the form: Type.GetType("name.space." + formname), so if your class is name.space.CloudAccessForm, then pass in CloudAccessForm as formname, and it will give you the type. Then you can instantiate it with Activator.CreateInstance(type). Then cast it to a Form, and show it.

Upvotes: 1

cvocvo
cvocvo

Reputation: 1636

Here's the working code from what fejejosco said:

string asdf = "CloudAccess";
Type CAType = Type.GetType("namespace." + asdf);
Form nextForm2 = (Form)Activator.CreateInstance(CAType);
nextForm2.ShowDialog();

Thanks!

Upvotes: 5

Related Questions