3

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?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Anton Putov
  • 1,951
  • 8
  • 34
  • 62
  • How do you expect the button `InnerText` to contain the string `first load + Button postback1` or `first postback + Button postback2` if you don't even have them in your code? – Leniel Maccaferri Oct 17 '12 at 21:35
  • I expect new button elements on the form. – Anton Putov Oct 17 '12 at 21:40
  • You have them or am I wrong? You say you have: 3 buttons namely: `"Button first load"`, `"Button postback1"`and `"Button postback2"`. – Leniel Maccaferri Oct 17 '12 at 21:44
  • When page loads first i have only one button -[ "Button first load"].after first postback I expect have two buttons [ "Button first load"] + [ "Button postback1"],third - three buttons... – Anton Putov Oct 17 '12 at 21:46

1 Answers1

3

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

Community
  • 1
  • 1
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480