如何将String转换为Windows表单对象 [英] How to convert String to Windows form object

查看:79
本文介绍了如何将String转换为Windows表单对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void SubMenuClicked(object sender, EventArgs e)
            {
                  Form _form;
                  string name = "frm";      
                  name+=((MenuItem)sender).Text;
                  _form = (Form)(name);
                  _form.ShowDialog();
            }



我正在获取总和文本,并希望根据该文本打开该表格。


I am getting sum text and want to open that form on the basis of that text.

推荐答案

替换

Replace
_form = (Form)(name);
_form.ShowDialog();



with


with

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Form f = null;
foreach (Assembly a in assemblies)
{
    Type[] types = a.GetTypes();
    foreach (Type t in types)
    {
        if (t.IsPublic && t.BaseType == typeof(Form))
        {
            if (t.FullName.Contains(name))
            {
                f = (Form)a.CreateInstance(t.FullName);
            }
        }
    }
}

if (f != null)
    f.ShowDialog();


' with reflection

Dim myAssembly As Assembly = Assembly.GetExecutingAssembly()

For Each t As Type In myAssembly.GetTypes()
  If t.IsPublic And t.BaseType.Name = "Form" Then
    If t.Name = NomeForm Then
      _obj = t.InvokeMember("", BindingFlags.CreateInstance, System.Type.DefaultBinder, New Object, Nothing)
      frm = CType(_obj, Form)
      frm.MdiParent = Me
      frm.Show()
      Exit For
    End If
  End If
Next


您的代码无效,您无法实例化此类表单。如果你要做的是根据不同的菜单项选择在项目中创建和打开不同表单的实例,你可以使用这样的代码:

You code is invalid, you cannot instantiate forms like this. If what you are trying to do is create and open instances of different forms in your project based on different menu item selections, you can use some code like this:
switch(((MenuItem)sender).Text) {
    case "Item1":
        Form1 f1 = new Form1();
        f1.Show();
    case "Item2":
        Form2 f2 = new Form2();
        f2.Show();
}


这篇关于如何将String转换为Windows表单对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆