.Net Webform丢失数据

时间:2013-01-23 22:23:50

标签: c# .net object postback viewstate

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

 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)
    {

    }

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

1 个答案:

答案 0 :(得分:2)

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

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

有两种选择:

  • 将您想要的所有内容仅放在n if语句中的FIRST加载中:
  • 将初始化移至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++;
        }
      }
     }

另外,建议阅读:The ASP.NET Page Lifecycle