水如烟

秋里生活,恬淡宁静。那如洗碧空,那伏黄草地,风凉夜寂,心儿涌动,情绪萦绕。可以凭窗,可以临江,可以坐,可以仰卧,可以独处,可以相依。倚明月,抚清辉,人生多少情怀,尽在秋里?...

按控件实例名称及其属性名称实现动态赋值

    '按控件实例名称及其属性名称实现动态赋值<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

    '入口参数:ClassInstance  控件所在的类实例

    '         ControlName 控件实例名称,区分大小写

    '         PropertyName 要设值的控件属性名称,区分大小写(其实这里可以不必区分大小写的,只是为了养成习惯,我这样要求自己的)

    '         Value 新值,类型是一个Object,这倒是要注意的

    '出口参数: True则重设成功,False不成功

    '需要 Imports System.ReflectionImports System.ComponentModel

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

        Dim Result As Boolean = False '返回值。虽然默认是Flase,但我还是喜欢这样设它,主要是看着明了

        '下面我不注释了

        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 = True

                Catch ex As Exception

                    MsgBox(ex.Message)

                End Try

            End If

        End If

 

        Return Result

    End Function

 

    '测试

    Private Sub Test()

        SetValueControlProperty(Me, "Button1", "Text", "Hello")

        SetValueControlProperty(Me, "Button2", "Visible", False)

        Dim frm As New Form2

        SetValueControlProperty(frm, "MyTextBox", "Text", "应该还行吧?")

        frm.Show()

    End Sub

阅读更多
个人分类: VB.NET应用点滴
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭