写了一个通过反射设置控件属性的函数
 public void SetValueControlProperty(Object ClassInstance, String ControlName, String PropertyName, Object value)
        {
            Object Result;            Type myTypes = ClassInstance.GetType();            FieldInfo myFieldInfo = myTypes.GetField(ControlName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField);            if (myFieldInfo != null)
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(myTypes);
                PropertyDescriptor myProperty = properties.Find("Text", false);                if (myProperty != null)
                {
                    Object ctr;
                    ctr = myFieldInfo.GetValue(ClassInstance);   //取得控件实例
                    try
                    {
                        myProperty.SetValue(ClassInstance, value);
                        Result = ctr;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
现在动态产生一个button控件,通过
Control myButton = Activator.CreateInstance(t) as Control;
生成button控件,然后调用
SetValueControlProperty(myButton, myButton.Name, "Text", "kingmax");
但在
FieldInfo myFieldInfo = myTypes.GetField(ControlName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField);
这一行,取得的button控件的myFieldInfo却为空?
这是怎么回事?

解决方案 »

  1.   

    觉得没有这么麻烦吧,如下就可以吧:
    private void button1_Click(object sender, EventArgs e)
    {
    Button b = new Button();
    this.SetValueControlProperty(b, "Text", "btn1");
    }
    public void SetValueControlProperty(Object ClassInstance, String PropertyName, Object value)
    {
    Type myTypes = ClassInstance.GetType(); PropertyInfo info = myTypes.GetProperty(PropertyName); if (info != null)
    {
    info.SetValue(ClassInstance, value, null);
    }
    }
      

  2.   

    在ASP。NET里程序把他给隐藏起来了,,我就是放在单独的一个类里完成的