I have a webpage containing a panel and a button. When you click the button, I want to add a new instance of a UserControl to the panel.
The panel.Controls.Add method specifies that it adds an item to a collection.
I can do this using a local variable to store the number of instances of the control. Then when one it added it loops this many times creating new controls.
private void AddUCToUI(int counter)
{
for (int i = 0; i < counter; i++)
{
MyControl ctrlMyControl = (MyControl)LoadControl("MyControl.ascx");
ctrlMyControl.SetID(i);
myPanel.Controls.Add(ctrlMyControl);
}
}
BUT, I don’t want to recreate all of the controls every time, as the user may have already entered data into them…
So all I want to do is create another control, and add it to the collection which already contains the first one.
private void AddUCToUI(int counter)
{
MyControl ctrlMyControl = (MyControl)LoadControl("MyControl.ascx");
ctrlMyControl.SetID(counter);
myPanel.Controls.Add(ctrlMyControl);
}
This should create a new control, give it an ID, then add it to the collection. However it seems to add a control in the first instance, then overwrite this control in the collection when I attempt to add another. Why is this?
I have managed to solve this issue:
Moving the code from
onInittoPage_Loadand using a session variable forcountersolved the issue of incrementing it’s value. Session variables are not reset when a PostBack happens.Here is my solution: