反射的应用--根据控件名取得控件
今天在项目中有用到根据控件名称取控件的问题,经过查找相关资料,实现方法如下,此代码为c#,转换为vb.net可以同样使用。
//必须引用命名空间System.Reflection,System.ComponentModel
/// <summary>
/// 根据控件名和属性名取值
/// </summary>
/// <param name="ClassInstance">控件所在实例</param>
/// <param name="ControlName">控件名</param>
/// <param name="PropertyName">属性名</param>
/// <returns>属性值</returns>
public static Object GetValueControlProperty(Object ClassInstance, string ControlName, string PropertyName)
{
Object Result=null;
Type myType = ClassInstance.GetType();
FieldInfo myFieldInfo = myType.GetField(ControlName, BindingFlags.NonPublic | //"|"为或运算,除非两个位均为0,运算结果为0,其他运算结果均为1
BindingFlags.Instance );
if(myFieldInfo !=null)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(myFieldInfo.FieldType);
PropertyDescriptor myProperty = properties.Find(PropertyName, false);
if(myProperty!=null)
{
Object ctr;
ctr = myFieldInfo.GetValue(ClassInstance);
try
{
Result = myProperty.GetValue(ctr);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
return Result;
}
/// <summary>
/// 根据控件名和属性名赋值
/// </summary>
/// <param name="ClassInstance">控件所在实例</param>
/// <param name="ControlName">控件名</param>
/// <param name="PropertyName">属性名</param>
/// <param name="Value">属性值</param>
/// <returns>属性值</returns>
public static Object SetValueControlProperty(Object ClassInstance , string ControlName, string PropertyName, Object Value)
{
Object Result=null;
Type myType = ClassInstance.GetType();
FieldInfo myFieldInfo = myType.GetField(ControlName, BindingFlags.NonPublic
| BindingFlags.Instance );
if(myFieldInfo!=null)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(myFieldInfo.FieldType);
PropertyDescriptor myProperty = properties.Find(PropertyName, false); //这里设为True就不用区分大小写了
if(myProperty!=null)
{
Object ctr;
ctr = myFieldInfo.GetValue(ClassInstance); //取得控件实例
try
{
myProperty.SetValue(ctr, Value);
Result = ctr;
}
catch( Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
return Result;
}
//调用
//以下实现Label1.Text=TextBox1.Text,Label2.Text=TextBox2
// private void Button1_Click(System.Object sender , System.EventArgs e)
// {
// int i;
//
// for( i = 1;i<= 2;i++)
// {
// this.SetValueControlProperty(this, "Label" + i.ToString(), "Text", GetValueControlProperty(this, "TextBox" + i.ToString(), "Text"));
// }
// }
posted on 2007-03-06 12:56 lovingbird 阅读(2734) 评论(6) 编辑 收藏 举报