Search code examples
asp.netuser-controlsweb-user-controls

ASP.NET User Controls - Problem adding multiple instances programmatically?


I have created a user control which basically consists of 3 text boxes. I want to allow the user to click a hyperlink which will add a new instance of the user control onto a PlaceHolder. This seems to be working as I populate one of the text box controls with a random number which changes whenever I click the hyperlink. However, it is overwriting the previous control.

Heres the code on MyPage.aspx

protected void MyHyperlink_Click(object sender, EventArgs e)
{
     var uc = new MyUserControl();
     uc = (MyUserControl)LoadControl("~/path/to/my/usercontrol.ascx");
     placeHolderCtrl.Controls.Add(uc);
}

Basically what I need to know is how can I get the control adding different instances underneath eachother as it just seems to be 1 control being overwritten each time.

Thanks.


Solution

  • The problem is after the postback, your previously added controls are not added to the placeholder. Dynamically added control should be added on each postback. My recommendation is to store a counter in a variable and at your page load, add your web controls again depending to this counter.