【问题标题】:How to open form by string name?如何按字符串名称打开表单?
【发布时间】:2016-05-30 10:06:04
【问题描述】:

如果我从文本框中获取字符串值并且我的表单名称与文本框中的字符串值相同。 如何打开这个表格?

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

我需要打开表格'AAA';

【问题讨论】:

    标签: c# winforms


    【解决方案1】:
       string formtocall = "blabla";
    
        var form = Activator.CreateInstance(Type.GetType("namespace." + formtocall)) as Form;
    
        form.ShowDialog();
    

    【讨论】:

    • 如果您认为这回答了您的问题,请将其标记为答案,以帮助其他人快速找到正确答案,并为 Hüseyin 打分。
    【解决方案2】:

    你需要使用反射。

    打开一个表单就是创建它的一个实例,你需要创建实例并显示它。

    您将需要表单的名称及其命名空间。

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

    然后你用激活器创建你的实例。

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

    然后你只需要显示表格

    frm.show();
    

    【讨论】:

      【解决方案3】:

      在下面使用:

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

      【讨论】:

        【解决方案4】:

        你也可以这样用:

        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;
        
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多