0

我在让我的页面保持状态时遇到问题。默认情况下启用视图状态,但每次单击按钮时都会重置表单。这是我的代码

 protected void Page_Load(object sender, EventArgs e)
    {


        Levels loadGame = new Levels(currentGame);

        int [] gameNums =  loadGame.getLevelNums();
        int inc = 1;
        foreach(int i in gameNums){

            if (i != 0)
            {
                TextBox tb = (TextBox)FindControl("TextBox" + inc);
                tb.Text = i.ToString();
                tb.Enabled = false;
            }
            else {
                //leave blank and move to next box
            }

            inc++;
        }

这是初始负载

protected void NormalButton_Click(object sender, EventArgs e)
    {

        clearBoxes();//clear boxes first
        setCurrentGame("normal");//setting to normal returns normal answers
         Levels loadGame = new Levels(returnCurrentGame());

        int[] gameNums = loadGame.getLevelNums();
        int inc = 1;
        foreach (int i in gameNums)
        {

            if (i != 0)
            {
                TextBox tb = (TextBox)FindControl("TextBox" + inc);
                tb.Text = i.ToString();
                tb.Enabled = false;
            }
            else
            {
                //leave blank and move to next box
            }

            inc++;
        }

    }

单击此按钮可更改不同框中的数字。

 protected void Button1_Click(object sender, EventArgs e)
    {

    }

然后我有这个空按钮,但每次我点击它时,它都会重置表单,即使我还没有设置它来做任何事情。我希望盒子保持不变,我也想让物体保持活力。我不确定我错过了什么,但请指出我正确的方向。提前致谢

4

1 回答 1

2

每次加载页面时都会发生 Page_Load 事件,包括事件驱动的回发(按钮单击等)。

看起来初始化代码在您的 Page_Load 中,因此当您单击该按钮时,它会再次运行。

有两种选择:

  • 将您希望仅在第一次加载时发生的所有事情放在 if 语句中:
  • 将您的初始化移动到 Page_Init。

第一个选项的代码示例:

 protected void Page_Load(object sender, EventArgs e)
    {
      if(!Page.IsPostBack)  // Teis is the key line for avoiding the problem
      {
        Levels loadGame = new Levels(currentGame);

        int [] gameNums =  loadGame.getLevelNums();
        int inc = 1;
        foreach(int i in gameNums){

            if (i != 0)
            {
                TextBox tb = (TextBox)FindControl("TextBox" + inc);
                tb.Text = i.ToString();
                tb.Enabled = false;
            }
            else {
                //leave blank and move to next box
            }

            inc++;
        }
      }
     }

另外,推荐阅读:ASP.NET 页面生命周期

于 2013-01-23T22:26:38.823 回答