0

I have an asp.net site and a user control added to the page. Then I also have a button which adds a second user control to the page once clicked.

protected void btnAdd_Click(object sender, EventArgs e)
        {
            Metric newControl = (Metric)LoadControl("~/Metric.ascx");
            Random rnd = new Random();
            newControl.ID = "id" + rnd.Next();
            placeholder.Controls.Add(newControl);
        }

The problem is that each user control has a dropdownlist which causes postback so when that happens the user control added with the btnAdd button is no longer present.

I understand it is because it only exists when the btnAdd_Click method is called so how can I overcome that?

2

1 Answer 1

0

Handling dynamically created controls on WebForms is complex. So the first recommendation is to solve the problem without using dynamically added controls, e.g. with a Repeater or Visible/Invisible controls (not very beautiful, but stable).

If this is not possible, you need to recreate the dynamically added controls early in the Page Lifecycle (e.g. in Page_Init) in order to wire up events reliably. So you'd need to change the way you assign the IDs of the UserControls as you need a deterministic approach to assign the same ID to the controls you recreate. You could use IDs like Metric1, Metric2, ... (the last count of ' PlaceHolder.Controls` is the number you assign). In order to be able to access the number of controls that have been added, you need to store it so you can access it in Page_Init, e.g. in a hidden field that you place on the page.

Then you need to add the code to recreate the controls in Page_Init. Therefore, you'd need to know how many controls are already placed on the page. You can retrieve this from the Form-collection of the request and then recreate the controls.

For a detailed overview on how to handle dynamic controls see this link.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.