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?

4
  • 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? Commented Oct 17, 2012 at 21:35
  • I expect new button elements on the form. Commented Oct 17, 2012 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". Commented Oct 17, 2012 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... Commented Oct 17, 2012 at 21:46

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

but every time this is reference to new object - myButton = new HtmlButton();

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.