I have a page in which controls are dynamically generated as the user navigates through a series of questions.
When they finish the form, they click a submit button, and I gather the information they entered and store it in a database.
Currently, I’m creating several of these controls with
.AutoPostBack = True
As a result, every time the user changes the text and tabs to the next field, a postback occurs, and the next field loses focus.
If I set
.AutoPostBack = False
then the focus problem goes away, but at the end when I gather the data, none of what the user entered in those controls is actually available to client side code, because it hasn’t been posted yet.
I’d like to do one of the following:
- Have one big postback at the end
- Have standard postbacks without losing focus on controls as I leave them
- Something else I haven’t thought of…?
Any suggestions?
The key to dynamically created controls is when in the page lifecyle to add the controls. To retain viewstate and have the dynamic controls maintain the posted values, the controls need to be added no later than
OnInit().In addition, the controls need to be re-added on every page load, postback or not. Regarding what @KennyZ said about guaranteeing the same ID for each control, as long as you are adding the same number of controls in the same order, .NET will guarantee the IDs are the same.
In regards to the
AutoPostBackproperty, this is usually only set to True when we want to perform some action that is triggered by the user changing the value of the control. A common example is a drop-down list; depending on what the user selected, different data is loaded into, say, the details section of the page. So each time the user changes the value, we want to postback and fetch new data to display.From my understanding of your use case, I would suggest one postback for the entire form.