Implement dynamic assignment by control instance name and its attribute name

zhaozj2021-02-16  102

'Implement dynamic assignment by control instance name and its attribute name

'Entry parameters: ClassInstance control class instance

'ControlName control instance name, case sensitive

'PropertyName The control attribute name to set the value, the case is case sensitive (in fact, you can do not need to be sized, just to develop habits, I ask yourself this)

The new value of 'Value, the type is an object, this is to pay attention to

'Export Parameters: True Reset Success, False is unsuccessful

'Require Imports System.Reflection and Imports System.comPonentModel

Public Function SetValueControlProperty (Byval ClassInstance As Object, Byval PropertyName As String, Byval Value As Object) AS Boolean

Dim Result as boolean = false 'Return Value. Although the default is Flase, I still like this, mainly watching it.

'I don't comment below.

DIM mytype as type = classinstance.gettype

Dim MyfieldInfo as FieldInfo = Mytype.Getfield ("_" & controlname, bindingflags.nonpublic OR_

Bindingflags.instance or bindingflags.public or bindingflags.instance) 'add "_" this is a special

IF not myfieldinfo is nothing then

DIM Properties as PropertyDescriptorCollection = typeDescriptor.getProperties (MyTYPE)

DIM MyProperty As PropertyDescriptor = Properties.Find (PropertyName, False) 'This is set to true if you don't have to write.

IF not myproperty is nothing then

DIM CTR As Object

CTR = myfieldinfo.getValue (classinstance) 'acquired an example

Try

MyProperty.SetValue (CTR, VALUE)

Result = TRUE

Catch 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 it be ok?")

frm.show ()

End Sub

转载请注明原文地址:https://www.9cbs.com/read-11484.html

New Post(0)