SDanks
SDanks

Reputation: 671

How do I pass the name of a form to a method that would instatiate it and set some properties of it?

I want to make a method that I can pass the name of a form to, and that method would instantiate the form and set it's position.

So I would call it like:

OpenNewForm("Login");

the method would look something like:

Public void OpenNewForm(string sForm)
{
[sForm] frm = new [sForm];
frm.Parent = parent;
frm.StartPosition = FormStartPosition.CenterParent;
frm.ShowDialog();

}

But I dont know how to refer to the variable sForm as part of the instatiation code.

Upvotes: 0

Views: 859

Answers (2)

Tony
Tony

Reputation: 17637

public static void OpenNewForm(string formName)
{
    string myNamespace = App.Current.GetType().ToString().Split('.')[0]; // TODO: Improve this method of get the namespace.

    var w = (Window)Activator.CreateInstance(null, myNamespace + "." + formName).Unwrap();
    w.Show();
}

Upvotes: 1

Tony
Tony

Reputation: 17637

Simple method (adapted from

public static void OpenNewForm(string formName)
{
    Form frm;
    switch (formName) {
        case "Login":
            frm = new Login();
        case "Citations":
            frm = new Citations();
        case "References":
            frm = new References();
        default:
            throw new ArgumentException("Invalid parameter value.");
    }

    frm.Parent = parent;
    frm.StartPosition = FormStartPosition.CenterParent;
    frm.ShowDialog();
}

Upvotes: 1

Related Questions