Mtok
Mtok

Reputation: 1630

Calling a form from a string in c#

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 ?

Upvotes: 5

Views: 9406

Answers (5)

Kay Programmer
Kay Programmer

Reputation: 21

For more dynamic so you can place your form in any folder :

public static void OpenForm(string FormName)
{
    var _formName = (from t in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                     where t.Name.Equals(FormName)
                     select t.FullName).Single();
    var _form = (Form)Activator.CreateInstance(Type.GetType(_formName));
    if (_form != null) 
    _form.Show();
}

Upvotes: 2

pablo sarmiento
pablo sarmiento

Reputation: 1

(Form)Assembly.GetExecutingAssembly().CreateInstance()

    Form frm = (Form)Assembly.GetExecutingAssembly().CreateInstance("namespace.form");
    frm.Show();

Upvotes: 0

Fede
Fede

Reputation: 44028

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();

Upvotes: 4

Brad Christie
Brad Christie

Reputation: 101594

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");

Upvotes: 7

snurre
snurre

Reputation: 3105

Try this:

var form = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(formToCall);
form.Show();

Upvotes: 1

Related Questions