-2

// get the name of the chosen form

            string myMenu = Convert.ToString(treeView1.SelectedNode.Tag);
            Form frm = new Form();
            frm.Name = myMenu;
            frm.MdiParent = this;
            frm.Show();
            frm.BringToFront();

// opens a blank form and not the one in the solution.

Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
Vicius
  • 1
  • 3
    The `Form` class is the base class of your Form. You are creating an instance of that class and not your class. Do you want instantiate an instance of your class, but not using `var frm = new MyForm();`, instead creating it simply from the string `"MyForm"`? If so, look at `Activator.CreateInstance` – Flydog57 Sep 09 '20 at 20:05
  • Please show how and where is `treeView1.SelectedNode.Tag` set. – JAlex Sep 09 '20 at 20:10

1 Answers1

-1

Here you go, you can try this

try{
    String formName = "OtherForm";
    String nameSpaceName = typeof(MainForm).Namespace;
    nameSpaceName = this.GetType().Namespace;
    // ^ THIS IS THE NAMESPACE THAT YOUR FORMS ARE IN. IF THERE ARE MANY, LOOP THEM.
    // THERE IS DEFINITELY A BETTER WAY TO FIND THE NAMESPACE, THESE ARE JUST 2 EXAMPLES
    // If it works for you, you can hard code it like String nameSpaceName = "MyNamespaceName"
    ((Form)Activator.CreateInstance(Type.GetType(nameSpaceName+'.'+formName))).Show();
}
catch(ArgumentNullException){MessageBox.Show("ERROR: Invalid namespace or class in string Type.GetType(this string)!");}
jake
  • 25
  • 1
  • 5
  • Thanks, it worked and looked like this: string myMenu = Convert.ToString(treeView1.SelectedNode.Tag); String formName = myMenu; String nameSpaceName = typeof(Form).Namespace; nameSpaceName = this.GetType().Namespace; Form frm = ((Form)Activator.CreateInstance(Type.GetType(nameSpaceName + '.' + formName))); frm.MdiParent = this; frm.Show(); frm.BringToFront(); – Vicius Sep 10 '20 at 11:16