我要以编程方式向控件添加验证的哪个事件?
我需要以编程方式在页面上的文本框中添加 requiredvalidator,我是否在 page_load 或之前的某个事件中执行此操作?
I need to add requiredvalidator on a textbox programatically on a page, do I do that in page_load or some event before that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于您为什么需要添加它。 如果它总是在那里,那么 OnInit 是一个好地方。
如果您只需要在某个操作发生后添加它,那么您希望在调用 LoadViewState 之后执行此操作,以便您可以在第一次添加后继续添加它。 对于第一次添加,您很可能会因为某些回发事件而想要这样做,因此您可以将其添加到事件处理程序中。
我建议在您需要该控件的位置添加一个占位符。 然后在需要时添加该控件。 然后,您应该在 ViewState 中存储一些信息,以了解您添加了该控件。 然后,您可以重写 LoadViewState,并在需要时添加控件。
如果仅当控件加载了一些数据时才需要验证器,那么您可以在加载数据后立即添加它,无论是 OnLoad 还是某些属性访问器。
That depends on why you need to add it. If it is always going to be there, then OnInit is a good place.
If you need to add it only after an action has occured then you want to do it after LoadViewState has been called so you can continue to add it once you add it the first time. For the first time add, most likely you will want to do it because of some post back event, so you could add it in your event handler.
I would suggest adding a placeholder to the control at the location of where you will want this control. Then you add the control when it is required. You should then store some information in ViewState to know that you added the control. You can then override LoadViewState, and add the control there if it is needed.
If you need the Validator only if the control is loaded with some data, then you add it right after the data has been loaded, be that OnLoad or some property accessor.
Page_Load 适合更改控件的设置。
编辑:
此代码经过测试并且有效:
但是如果您在事件发生后动态生成验证器,问题可能会有所不同。
Page_Load is good for changing controls' settings.
EDIT :
This code tested and works :
But if you're generating your validators after an event dynamically, problem might be different.