Hi,
I need to add requiredvalidator on a textbox programatically on a page, do I do that in page_load or some event before that?
Hi,
I need to add requiredvalidator on a textbox programatically on a page, do I do that in page_load or some event before that?
Page_Load is good for changing controls' settings.
EDIT : This code tested and works :
// in page_load event :
validator.ControlToValidate = textboxToValidate.ID;
But if you're generating your validators after an event dynamically, problem might be different.
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.