views:

566

answers:

1

Hi,

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.

+2  A: 

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.

Canavar
I had to store the count in the Session, but it did seem to add as many controls as I clicked.
James
Actually I would prefer Viewstate, it will be used only at one page.
Canavar
Yeah I am going to change to use this, I just wasn't sure at first how I would be able to determine when it is first load of the page. However, I have figured it out! Thanks.
James