'按控件實例名稱及其屬性名稱實現動態賦值
'入口參數:classinstance 控件所在的類實例
' controlname 控件實例名稱,區分大小寫
' propertyname 要設值的控件屬性名稱,區分大小寫(其實這里可以不必區分大小寫的,只是為了養成習慣,我這樣要求自己的)
' value 新值,類型是一個object,這倒是要注意的
'出口參數: true則重設成功,false不成功
'需要 imports system.reflection和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 '返回值。雖然默認是flase,但我還是喜歡這樣設它,主要是看著明了
'下面我不注釋了
dim mytype as type = classinstance.gettype
dim myfieldinfo as fieldinfo = mytype.getfield("_" & controlname, bindingflags.nonpublic or _
bindingflags.instance or bindingflags.public) '加"_"這個是特要緊的
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