title: Dynamically adding and persisting TextBoxes to a user control
body: <p>Working with C# .NET 4.0 and Umbraco</p>
  
  <p>I have a user control on which there is a button allowing user to dynamically add additional text boxes to the form. I've tried a myriad of methods but have been unable to persist any data entered into the dynamic text boxes between page loads.</p>
  
  <p>Here's the UI:</p>
  
  <pre><code>&lt;div id="new-item"&gt;
  &lt;h3&gt;Add new menu item&lt;/h3&gt;
  &lt;div&gt;&lt;label for="ItemTitle"&gt;Title&lt;/label&gt;&lt;asp:TextBox ID="ItemTitle" runat="server" CssClass="title"&gt;&lt;/asp:TextBox&gt;&lt;/div&gt;
  &lt;div&gt;&lt;label for="ItemDescription"&gt;Text&lt;/label&gt;&lt;textarea id="ItemDescription" runat="server" rows="5" cols="20"&gt;&lt;/textarea&gt;&lt;/div&gt;
  &lt;div&gt;&lt;label for="ItemPrice"&gt;Price&lt;/label&gt;&lt;asp:TextBox ID="ItemPrice" runat="server" CssClass="price"&gt;&lt;/asp:TextBox&gt;&lt;/div&gt;
  &lt;div class="new-item-options"&gt;
      &lt;p&gt;&lt;strong&gt;Menu item options (optional) &lt;/strong&gt;&lt;asp:Button ID="AddMenuItemOption" runat="server" Text="Add Option" OnClick="AddOption" /&gt;&lt;/p&gt;
      &lt;asp:Panel ID="MenuItemOptionsPanel" runat="server"&gt;&lt;/asp:Panel&gt;
      &lt;asp:HiddenField ID="ItemOptionCount" runat="server" /&gt;
  &lt;/div&gt;
  &lt;div&gt;&lt;asp:Button ID="AddItemButton" runat="server" Text="Save" /&gt;&lt;/div&gt;
  &lt;asp:HiddenField ID="ItemID" runat="server" /&gt;
  &lt;asp:HiddenField ID="ItemOrder" runat="server" /&gt;
  </code></pre>
  
  <p></p>
  
  <p>And in the AddOption button click event:</p>
  
  <pre><code>protected void AddOption(object sender, EventArgs e)
  {
      var dynamicControlCount = Convert.ToInt32(ItemOptionCount.Value) + 1;
  
      for (var option = 0; option &lt; dynamicControlCount; option++)
      {
          MenuItemOptionsPanel.Controls.Add(new Literal { ID = "OptionTextLiteral" + option, Text = "&lt;label&gt;Option Text&lt;/label&gt;" });
          MenuItemOptionsPanel.Controls.Add(new TextBox { ID = "OptionTextBox" + option });
          MenuItemOptionsPanel.Controls.Add(new Literal { ID = "OptionPriceLiteral" + option, Text = "&lt;label&gt;Option Price&lt;/label&gt;" });
          MenuItemOptionsPanel.Controls.Add(new TextBox { ID = "OptionPriceBox" + option });
      }
  
      ItemOptionCount.Value = dynamicControlCount.ToString();
  }
  </code></pre>
  
  <p>I know I need to create these dynamic controls in the Page_Load or OnInit methods but the problem is when the page loads for the first time, I don't want any dynamic controls create, only once the user clicks the button each time I'm like additional control added and those that already exist to have any data in them persisted.</p>
  
  <p>Any ideas? I don't think I'm too far off hopefully :)</p>