硬件学院 | 网络学院 | 游戏秘籍 | 求职技巧 | 企业管理 | 软件资讯 | IT导购 | 软件下载 | 源码下载
软件学院 | 安全资讯 | 图形图象 | 网络营销 | 电子商务 | 硬件资讯 | IT生活 | 教程下载 | 电影娱乐
网站首页    个人求职    单位招聘    高校联盟    猎头服务    培训服务    资讯中心    IT论坛
让每一个热爱IT的人都找到一份满意的工作!
文章搜索:
 您的位置首页->-> 软件学院-> .NET技术-> 反射应用之一:根据控件名、属性名进行取值和赋值
反射应用之一:根据控件名、属性名进行取值和赋值
作者:中国资讯网 来源:zixuen.com 加入时间:2005-5-12 www.cnitrc.com
'必须引用命名空间System.Reflection,System.ComponentModel

'以下根据控件名和属性名取值

Public Function GetValueControlProperty(ByVal ClassInstance As Object, ByVal ControlName As String, ByVal PropertyName As String) As Object

Dim Result As Object

Dim myType As Type = ClassInstance.GetType

Dim myFieldInfo As FieldInfo = myType.GetField("_" & ControlName, BindingFlags.NonPublic Or _

BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.Instance)

If Not myFieldInfo Is Nothing Then

Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(myType)

Dim myProperty As PropertyDescriptor = properties.Find(PropertyName, False)

If Not myProperty Is Nothing Then

Dim ctr As Object

ctr = myFieldInfo.GetValue(ClassInstance)

Try

Result = myProperty.GetValue(ctr)

Catch ex As Exception

MsgBox(ex.Message)

End Try

End If

End If

Return Result

End Function

'以下根据控件名和属性名赋值

Public Function SetValueControlProperty(ByVal ClassInstance As Object, ByVal ControlName As String, ByVal PropertyName As String, ByVal Value As Object) As Object

Dim Result As Object

Dim myType As Type = ClassInstance.GetType

Dim myFieldInfo As FieldInfo = myType.GetField("_" & ControlName, BindingFlags.NonPublic _

Or BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.Instance) '加"_"这个是特要紧的

If Not myFieldInfo Is Nothing Then

Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(myType)

Dim myProperty As PropertyDescriptor = properties.Find(PropertyName, False) '这里设为True就不用区分大小写了

If Not myProperty Is Nothing Then

Dim ctr As Object

ctr = myFieldInfo.GetValue(ClassInstance) '取得控件实例

Try

myProperty.SetValue(ctr, Value)

Result = ctr

Catch ex As Exception

MsgBox(ex.Message)

End Try

End If

End If

Return Result

End Function

'调用

'以下实现Label1.Text=TextBox1.Text,Label2.Text=TextBox2

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim i As Integer

For i = 1 To 2

Me.SetValueControlProperty(Me, "Label" & i.ToString, "Text", GetValueControlProperty(Me, "TextBox" & i.ToString, "Text"))

Next i

End Sub
  相关文章:
.NET技术
ASP技术
PHP技术
JSP技术
.NET技术
服务器技术
数据库技术
其它类
工具软件
办公软件
本类阅读TOP10
 
关于我们   |   服务声明   |   使用帮助   |   广告合作   |   网站地图   |   友情链接   |   加盟合作   |   联系我们
Copyright © 2006 cnitrc.com Inc. All Rights Reserved. 浙ICP备05074295号
中国IT人才网 版权所有 网络实名:中国IT人才
未经书面授权严禁转载和复制本站的任何招聘信息和文章