首页 > 开发 > 综合 > 正文

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

2024-07-21 02:24:10
字体:
来源:转载
供稿:网友

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

'入口参数: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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表