3

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I had to store the count in the Session, but it did seem to add as many controls as I clicked.
Actually I would prefer Viewstate, it will be used only at one page.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.