反射的应用根据控件名取得控件,获取值及赋值

本文转自:http://www.cnblogs.com/waban/archive/2007/03/06/665326.html

1 //必须引用命名空间System.Reflection,System.ComponentModel
2  
3 /// <summary>
4 /// 根据控件名和属性名取值
5 /// </summary>
6 /// <param name="ClassInstance">控件所在实例</param>
7 /// <param name="ControlName">控件名</param>
8 /// <param name="PropertyName">属性名</param>
9 /// <returns>属性值</returns>
10 public static Object GetValueControlProperty(Object ClassInstance, string ControlName, string PropertyName)
11 {
12 Object Result=null;
13
14 Type myType = ClassInstance.GetType();
15
16 FieldInfo myFieldInfo = myType.GetField(ControlName, BindingFlags.NonPublic | //"|"为或运算,除非两个位均为0,运算结果为0,其他运算结果均为1
17 BindingFlags.Instance );
18
19 if(myFieldInfo !=null)
20 {
21 PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(myFieldInfo.FieldType);
22
23 PropertyDescriptor myProperty = properties.Find(PropertyName, false);
24
25 if(myProperty!=null)
26 {
27 Object ctr;
28
29 ctr = myFieldInfo.GetValue(ClassInstance);
30
31 try
32 {
33 Result = myProperty.GetValue(ctr);
34 }
35 catch(Exception ex)
36 {
37 MessageBox.Show(ex.Message);
38 }
39 }
40 }
41
42 return Result;
43 }
44
45 /// <summary>
46 /// 根据控件名和属性名赋值
47 /// </summary>
48 /// <param name="ClassInstance">控件所在实例</param>
49 /// <param name="ControlName">控件名</param>
50 /// <param name="PropertyName">属性名</param>
51 /// <param name="Value">属性值</param>
52 /// <returns>属性值</returns>
53 public static Object SetValueControlProperty(Object ClassInstance , string ControlName, string PropertyName, Object Value)
54 {
55 Object Result=null;
56
57 Type myType = ClassInstance.GetType();
58
59 FieldInfo myFieldInfo = myType.GetField(ControlName, BindingFlags.NonPublic
60 | BindingFlags.Instance );
61 if(myFieldInfo!=null)
62 {
63 PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(myFieldInfo.FieldType);
64
65 PropertyDescriptor myProperty = properties.Find(PropertyName, false); //这里设为True就不用区分大小写了
66
67 if(myProperty!=null)
68 {
69 Object ctr;
70
71 ctr = myFieldInfo.GetValue(ClassInstance); //取得控件实例
72
73 try
74 {
75 myProperty.SetValue(ctr, Value);
76
77 Result = ctr;
78 }
79 catch( Exception ex)
80 {
81 MessageBox.Show(ex.Message);
82 }
83 }
84 }
85 return Result;
86 }
87
88 //调用
89
90 //以下实现Label1.Text=TextBox1.Text,Label2.Text=TextBox2
91
92 // private void Button1_Click(System.Object sender , System.EventArgs e)
93 // {
94 // int i;
95 //
96 // for( i = 1;i<= 2;i++)
97 // {
98 // this.SetValueControlProperty(this, "Label" + i.ToString(), "Text", GetValueControlProperty(this, "TextBox" + i.ToString(), "Text"));
99 // }
100 // }
原文地址:https://www.cnblogs.com/martintuan/p/1970348.html