您的位置:首页 > 其它

根据控件名字和属性动态修改值

2008-10-15 21:12 281 查看
public object GetCompProperty(object form, string compName, string propertyName)
{
    Type formType = form.GetType();
    FieldInfo compInfo = formType.GetField(compName, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    Component obj = (Component)compInfo.GetValue(form);

    Type compType = obj.GetType();
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(obj);
    PropertyDescriptor propertyDescriptor = propertyDescriptorCollection.Find(propertyName, false);

    if (propertyDescriptor != null)
    {
        return propertyDescriptor.GetValue(obj);
    }
    return null;
}

public void SetCompProperty(object form, string compName, string propertyName, object value)
{
    Type formType = form.GetType();
    FieldInfo compInfo = formType.GetField(compName, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    Component obj = (Component)compInfo.GetValue(form);

    Type compType = obj.GetType();
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(obj);
    PropertyDescriptor propertyDescriptor = propertyDescriptorCollection.Find(propertyName, false);

    if (propertyDescriptor != null)
    {
        propertyDescriptor.SetValue(obj, value);
    }
}

private void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show(GetCompProperty(this, "button1", "Width").ToString());

    SetCompProperty(this, "button1", "Width", 100);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: