0

I am developing a dynamic website in ASP.NET. As a trial I tried a code shown below, that adds some controls to Panel1. When user clicks a button for the first time the controls are added to the Panel but when user clicks the same button for second time, the previous controls are replaced with new ones. But I want the controls to be appended one after the other each time the user clicks the button. The code is something like this:

Control c=Page.LoadControl("DData.ascx");
Panel1.Controls.Add(c);

I also tried

Control c=Page.LoadControl("DData.ascx");
Panel1.Controls.AddAt(Panel1.Controls.Count,c);

But this replaces the first output. Please tell me how to append these controls?

Shiva Pareek
  • 1,719
  • 5
  • 21
  • 42
  • Did you try to give an unique name to each control (for example using a timestamp or an ID based on Panel1.Controls.Count) before you add the control to the collection? – Adriano Repetti Oct 14 '12 at 08:12
  • Your code is actually correct. Both the Controls.Add and the Controls.AddAt should do the job. I am with Adriano on this one, are you sure you are adding unique objects/controls to Controls? – Mike de Klerk Oct 14 '12 at 08:14
  • These controls are of same type but with different content inside them. Like the comments here on StackOverflow. – Shiva Pareek Oct 14 '12 at 08:17

2 Answers2

0

As you would expect, this appends a single control:

Control c = Page.LoadControl("DData.ascx");
Panel1.Controls.Add(c);

You can append as many controls as you wish in this fashion.

However, you need to keep track of the controls you are adding in some persisted/stateful fashion (database, Session, ViewState, etc.).

You need to rebuild the control tree every time the page loads.

See my answers to similar questions:

Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163
0

It may be about the life cycle of asp.net page. Each time when page loads it returns to the initial state. Button Click events are handled after page load and you have only one control at the page. Please look Button to dynamically add controls everytime it's clicked

aliassce
  • 1,197
  • 6
  • 19