How to open form by string name?

前端 未结 4 1319
盖世英雄少女心
盖世英雄少女心 2020-12-12 08:16

If i get string value from textbox and my Form name is same string value from textbox. How to open this form ?

string formAAA = textbox.text; // \"AAA\"


        
相关标签:
4条回答
  • 2020-12-12 08:37

    Use below:

        private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
                {
                    return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
                }
    
                private void Form1_Load(object sender, EventArgs e)
                {
    //Get all types
                    Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "loopClasses");
                    for (int i = 0; i < typelist.Length; i++)
                    {//Loop on them 
                        if (typelist[i].BaseType == typeof(System.Windows.Forms.Form) && typelist[i].Name == textbox.text)
                        {//if windows form and the name is match
    
    //Create Instance and show it
                            Form tmp =(Form) Activator.CreateInstance(typelist[i]);
                            //MessageBox.Show(typelist[i].Name);
                            tmp.Show();
                        }
                    }
    
                }
    
    0 讨论(0)
  • 2020-12-12 08:45

    You need to use reflection.

    Opening a form is creating an instance of it, you need to create the instance and show it.

    You are going to need the name of the form and its namespace.

    string formName= textbox.Text;
    string namespaceName = "MyNamespace.MyInternalNamespace";
    

    Then you create your instance with activator.

    var frm= Activator.CreateInstance(namespaceName, formName) as Form;
    

    And then you just need to show the form

    frm.show();
    
    0 讨论(0)
  • 2020-12-12 08:50

    You can also use this:

    Form GetFormByName(string name)
        {
            System.Reflection.Assembly myAssembly =System.Reflection.Assembly.GetExecutingAssembly();
            foreach(Type type in myAssembly.GetTypes())
            {
                if (type.BaseType!=null&& type.BaseType.FullName == "System.Windows.Forms.Form")
                {
                    if (type.FullName == name)
                    {
                        var form = Activator.CreateInstance(Type.GetType(name)) as Form;
                        return form;
                    }
                }
            }
                return null;
    
        }
    
    0 讨论(0)
  • 2020-12-12 08:55
       string formtocall = "blabla";
    
        var form = Activator.CreateInstance(Type.GetType("namespace." + formtocall)) as Form;
    
        form.ShowDialog();
    
    0 讨论(0)
提交回复
热议问题