Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET dynamic controls count (creating controls as you go)
    text
    copied!<p>I'm trying to create a composite ASP.NET control that let's you build an editable control collection.</p> <p>My problem is that when I press the add or postback button (which does nothing other than to postback the form) any values entered in the text boxes are lost.</p> <p>I can't get it to work when the number of controls change between postbacks. I need to basically be able to recreate the control tree at two different times in the control life-cycle depending on the view state property <code>ControlCount</code>.</p> <p>This test can be used to reproduce the issue:</p> <pre><code>public class AddManyControl : CompositeControl { protected override void OnLoad(EventArgs e) { base.OnLoad(e); EnsureChildControls(); } protected override void CreateChildControls() { var count = ViewState["ControlCount"] as int? ?? 0; for (int i = 0; i &lt; count; i++) { var div = new HtmlGenericControl("div"); var textBox = new TextBox(); textBox.ID = "tb" + i; div.Controls.Add(textBox); Controls.Add(div); } ViewState["ControlCount"] = count; var btnAdd = new Button(); btnAdd.ID = "Add"; btnAdd.Text = "Add text box"; btnAdd.Click += new EventHandler(btnAdd_Click); Controls.Add(btnAdd); var btnPostBack = new Button(); btnPostBack.ID = "PostBack"; btnPostBack.Text = "Do PostBack"; Controls.Add(btnPostBack); } void btnAdd_Click(object sender, EventArgs e) { ViewState["ControlCount"] = (int)ViewState["ControlCount"] + 1; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // If I remove this RecreateChildControls call // the collection lags behind each postback // because the count is incremented in the btnAdd_Click event handler // however, the values are not lost between postbacks RecreateChildControls(); } } </code></pre>
 

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