【问题标题】:How to get the Text property of each form如何获取每个表单的 Text 属性
【发布时间】:2014-07-29 04:05:36
【问题描述】:

我已经搜索了将近一个星期,但我似乎无法解决我的简单问题。我想获取项目中所有表单的所有名称和文本属性。

这是我的代码:

using System.Reflection;

Type Myforms = typeof(Form);
foreach (Type formtype in Assembly.GetExecutingAssembly().GetTypes())
{
    if (Myforms.IsAssignableFrom(formtype))
    {
      MessageBox.Show(formtype.Name.ToString()); // shows all name of form
      MessageBox.Show(formtype.GetProperty("Text").GetValue(type,null).ToString()); // it shows null exception
    }
}

我需要表单的名称和.Text 将其存储在数据库中以控制用户权限。

【问题讨论】:

  • 感谢您纠正 Dijkgraaf。

标签: c# winforms text types getproperty


【解决方案1】:

MessageBox.Show(formtype.GetProperty("Text").GetValue(type,null).ToString()); 显示异常,因为您需要 Form 的实例来获取其 Text 属性,因为 Form 没有静态 Text 属性。

要获取默认的 Text 属性,请创建一个实例

var frm = (Form)Activator.CreateInstance(formtype);
MessageBox.Show(formtype.GetProperty("Text").GetValue(frm, null).ToString());

【讨论】:

  • hi itried 该代码,它向我显示了一个错误 mscorlib.dll 中发生了“System.MissingMethodException”类型的未处理异常附加信息:没有为此对象定义无参数构造函数..我该如何解决这个问题
  • @Mandz 已修复,m8 再试一次!
  • AppDeveloper 我发现了问题。我删除了 public MaintainFormFrm() { InitializeComponent(); }
【解决方案2】:

属性.Text.Name 不是静态的。因此,如果不调用该表单的构造函数,您将无法获取该属性的值。您必须创建该表单的对象才能读取该属性。

List<String> formList = new List<String>();
Assembly myAssembly = Assembly.GetExecutingAssembly();

foreach (Type t in myAssembly.GetTypes())
{
    if (t.BaseType == typeof(Form))
    {
        ConstructorInfo ctor = t.GetConstructor(Type.EmptyTypes);
        if (ctor != null)
        {
            Form f = (Form)ctor.Invoke(new object[] { });
            formList.Add("Text: " +  f.Text + ";Name: " + f.Name);
        }
    }
}

【讨论】:

    【解决方案3】:

    要读取属性,您需要创建表单的新实例。在上面,您正在浏览从Form-class 继承的所有类型。您可以阅读不同的 Form-class 名称,仅此而已。

    要阅读Text-属性,您需要浏览Forms 的实例。您可以使用Application.OpenForms 来读取打开表单的TextName 属性。

    你可以试试这个来读取属性:

    List<KeyValuePair<string, string>> formDetails = new List<KeyValuePair<string, string>>();
    Type formType = typeof(Form);
    foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
    {
       if (formType.IsAssignableFrom(type))
       {
          using (var frm = (Form)Activator.CreateInstance(type))
          {
             formDetails.Add(new KeyValuePair<string, string>(frm.Name, frm.Text));
          }
       }
    }
    

    我修复了代码,现在应该可以使用了。

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多