2013-01-23 24 views
0

我在使頁面保持狀態時遇到問題。視圖狀態默認情況下處於啓用狀態,但每次單擊按鈕時都會重置表單。這是代碼我有.Net Webform丟失數據

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

    } 

然後,我有這個空的按鈕,但每次我點擊它,它重置儘管我還沒有把它做任何事情的形式。我希望箱子保持不變,並且我還想讓物體保持活力。我不確定我錯過了什麼,但請指出正確的方向。在此先感謝

回答

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

另外,推薦閱讀:The ASP.NET Page Lifecycle

+0

謝謝你這麼多戴夫...你幫助一個新手。 –

+0

沒問題。這就是爲什麼網站在這裏,我自己曾多次受過幫助。 – David