Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with the other points made here "If you can get out of creating controls dynamically, then do so..." (by @<a href="https://stackoverflow.com/users/11559/jesper-blad-jensen-aka-deldy">Jesper Blad Jenson aka</a>) but here is a trick I worked out with dynamically created controls in the past.</p> <p>The problem becomes chicken and the egg. You need your ViewState to create the control tree and you need your control tree created to get at your ViewState. Well, that's almost correct. There is a way to get at your ViewState values <i>just before</i> the rest of the tree is populated. That is by overriding <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadviewstate.aspx" rel="nofollow noreferrer" title="MSDN - Control.LoadViewState Method"><code>LoadViewState(...)</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.saveviewstate.aspx" rel="nofollow noreferrer" title="MSDN - Control.SaveViewState Method"><code>SaveViewState(...)</code></a>.</p> <p>In SaveViewState store the control you wish to create:</p> <pre><code>protected override object SaveViewState() { object[] myState = new object[2]; myState[0] = base.SaveViewState(); myState[1] = controlPickerDropDown.SelectedValue; return myState } </code></pre> <p>When the framework calls your "LoadViewState" override you'll get back the exact object you returned from "SaveViewState":</p> <pre><code>protected override void LoadViewState(object savedState) { object[] myState = (object[])savedState; // Here is the trick, use the value you saved here to create your control tree. CreateControlBasedOnDropDownValue(myState[1]); // Call the base method to ensure everything works correctly. base.LoadViewState(myState[0]); } </code></pre> <p>I've used this successfully to create ASP.Net pages where a DataSet was serialised to the ViewState to store changes to an entire grid of data allowing the user to make multiple edits with PostBacks and finally commit all their changes in a single "Save" operation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload