Anton Putov
Anton Putov

Reputation: 1981

Dynamic adding elements in ASP.NET

Look at this code:

        static int i = 0;
       protected void Page_Load(object sender, EventArgs e)
    {
        HtmlButton myButton;
        if (!Page.IsPostBack)
        {
            myButton = new HtmlButton();
            myButton.InnerText = "Button first load";
            myButton.ID = i.ToString();
            PlaceHolder1.Controls.Add(myButton);
            i++;
        }
        else
        {
            myButton = new HtmlButton();
            myButton.InnerText = "Button postback" + i.ToString();
            myButton.ID = i.ToString();
            PlaceHolder1.Controls.Add(myButton);
            i++;
        }
    }

expected:

       first load:  "Button first load"
       first postback: first load + "Button postback1"
       second postback: first postback + "Button postback2" ... and so on.

have:

      "Button first load"
      "Button postback1"
      "Button postback2".

Why?

Upvotes: 3

Views: 690

Answers (1)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102428

Your expected results are really wrong... :)

Right now what's happening is exactly what you have written in the code:

1st load (not postback):

 myButton.InnerText = "Button first load";

Then:

"Button first load"

2nd, 3rd, nth load (postback):

 myButton.InnerText = "Button postback" + i.ToString();

Then:

"Button postback1"
"Button postback2"
.
.
.

UPDATE:

Now that I understood your problem...

ASP.NET does not persist state of dynamic controls and thus cannot recreate them after the postback.

Bottom line: You must recreate your dynamically added controls after each postback.

Here's an answer I gave more than 2 years ago that shows you a nice way of handling such situation:

https://stackoverflow.com/a/2982271/114029

Upvotes: 3

Related Questions