1
votes

I'm adding dynamic controls to a page based on data from a database to generate RadioButtonList questions.

Sometimes the questions are required, in which case after the data is retrieved from the database and the RadioButtonList is populated, I dynamically add a RequiredFieldValidator for the RadioButtonList.

The problem arises on postback, when in Page_Load() I execute Page.Validate() which always fails. I discovered that this is because the controls are being re-added on post-back but they aren't repopulated with the user's responses.

My question is:

When can I grab the user's response once they click "Submit", where do I store it, and what's the best way to bring it back so that Page.Validate() validates against controls with the proper responses?

1
what do you mean page validate if you use just looking to validate you can just add required control dynamically and validate on client side with button submit if you want I can show you how I do it - COLD TOLD

1 Answers

3
votes

Instead of creating the validation controls in Page_Load (or in a function that's called from within page_Load) do so in Page_Init

For more info see the Page Lifecycle:

In the Page Lifecycle, putting it in Page_Init allows the controls to be created on each page load, but BEFORE the viewstate values are applied. This means that the controls are created, and then the user selection is applied.

If you have it in Page_Load, then the controls are created AFTER the Viewstate values are applied. This means that the controls are just created from scratch after the viewstate has been applied, resetting everything to the default value.

Actually, this page says it better:

  • During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

  • During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

  • Use Page_Init when you have to create controls dynamically. The controls are created every time that the page is run. The best place to do this is in the Page_Init function.