通过反射获得控制
我需要使用反射从我的页面通过其 ID 获取控件 [文本框、标签、按钮...等]
在我的例子中,我有一个所有其他系统页面都继承自它的类,并且该类将覆盖 onload 事件以进行更改某些控件的一些属性,
例如通过名称设置文本框的可见性状态,但由于我没有直接在页面上使用该控件,因为我可能将它放在母版页的内容占位符上,所以我也无法使用 findcontrol 方法认为递归函数查找控件会花费太多时间
,所以我尝试通过反射来查找具有其名称的控件,然后更改它的可见或启用状态
我使用了 FieldInfo 类,但没有不跟我一起工作
FieldInfo fi = this.GetType().GetField("ControlID", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
有什么帮助吗!
I need to get a control [textbox,label,button ...etc] from my page by it's ID using reflection
In my case I have a class that all other system pages inherit from it and this class is override the onload event to change some properties to some controls
like set the visibility state for textbox by it's name but as I don't have the control direct on the page as I may have it on content place holder in master page so I couldn't use findcontrol method also I think recursive function to find the control will take too much time
So I try to do it with refelection to find a control with its name then change the visable or enable state for it
I used the FieldInfo class but doesn't work with me
FieldInfo fi = this.GetType().GetField("ControlID", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
Any help !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过 查找控件
Have you tried FindControl
也许您需要使用 FindControl 递归地查找控件,然后调用自身?
并将其称为传递页面的当前实例:
但是,这可能会很慢 - 因此,如果页面上有一大堆控件,请务必注意:)
另一种方法是将控件简单地公开为属性你的基类:
最后的方法是挂钩到你的基类中的派生类:
然后在你的派生页面中重写:
如果没有那么多控件,我可能会使用第二个。第一种方法在处理中继器等时很有用。
maybe you need to recursively look for your control with FindControl, and then calling itself?
And call it passing the current instance of the page through:
This can be slow however - so do look out for that if there's a whole bunch of controls on the page :)
Another way to do it would be simply expose the controls as properties in your base class:
And the final way to do it would be to hook into derived classes in your base class:
And then override in your derived page:
Out of these i would probably use the second if there's not so many controls. The first method is useful when dealing with repeaters and the like.
这是递归获取子控件的非常有用的扩展方法:
用法:
Here's very useful extension method to get child controls recursively:
Usage: