To implement dynamic assignment by control instance name and its property name

Source: Internet
Author: User
Tags implement
Dynamic | Controls ' implement dynamic assignment by control instance name and its property name

' Entry parameter: class instance where the Classinstance control is located

' ControlName control instance name, case-sensitive

' PropertyName to set the value of the control property name, case-sensitive (in fact, here can not be case-sensitive, but in order to form a habit, I ask myself)

' Value, the type is an object, which should be noted.

' Exit parameter: True reset succeeded, false unsuccessful

' Requires imports System.Reflection and imports 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 ' Returns the value. Although the default is flase, but I still like to set it, mainly to look at the clear

' Below I don't comment

Dim MyType as Type = Classinstance.gettype

Dim Myfieldinfo as FieldInfo = Mytype.getfield ("_" & ControlName, BindingFlags.NonPublic Or _

BindingFlags.Instance Or bindingflags.public) ' Plus ' _ ' This is a special matter.



If not myfieldinfo are nothing Then

Dim properties as PropertyDescriptorCollection = Typedescriptor.getproperties (MyType)

Dim MyProperty as PropertyDescriptor = properties. Find (PropertyName, False) ' Set to true here is not case-sensitive



If not MyProperty are nothing Then

Dim Ctr as Object

CTR = Myfieldinfo.getvalue (classinstance) ' Gets control instance

Try

Myproperty.setvalue (CTR, Value)

result = True

Catch ex as Exception

MsgBox (ex. Message)

End Try

End If

End If



return result

End Function



' Test

Private Sub Test ()

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

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

Dim frm as New Form2

Setvaluecontrolproperty (frm, "MyTextBox", "Text", "should be OK?")

frm. Show ()

End Sub




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.