views:

152

answers:

2

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?

+1  A: 

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.

Canavar
page load doesn't seem to work for me, isn't it too late in the page lifecycle?
Blankman
no it's the common place to set properties, let me test it, I'll write the result.
Canavar
You can add a control at any point. You just need to make sure the control hierarchy is the same during subsequent post backs.
Daniel
ahh ok, my submit button has its own event so maybe that is the problem?
Blankman
+1  A: 

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.

Daniel