3

看看这段代码:

        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++;
        }
    }

预期的:

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

有:

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

为什么?

4

1 回答 1

3

你的预期结果真的是错误的...... :)

现在发生的事情正是你在代码中写的:

第一次加载(不是回发):

 myButton.InnerText = "Button first load";

然后:

"Button first load"

第 2、3、n 次加载(回发):

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

然后:

"Button postback1"
"Button postback2"
.
.
.

更新:

现在我明白了你的问题......

ASP.NET 不保留动态控件的状态,因此无法在回发后重新创建它们。

底线:您必须在每次回发后重新创建动态添加的控件。

这是我两年多前给出的答案,它向您展示了处理这种情况的好方法:

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

于 2012-10-17T21:32:25.243 回答