2012-04-09 57 views
0

我有一個簡單的gridview。 將tableData綁定到gridview的SqlDataSource。GridView:如何在行更新中每次增加一個單元格的值?

行更新我試圖增加一個單元格(int類型)的值。 這裏是我的代碼,但不幹活G:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
     { 
      GridViewRow row = GridView1.Rows[e.RowIndex]; 
      string str = ((TextBox)(row.Cells[8].Controls[0])).Text; 
      int conv = Convert.ToInt32(str); 
      int set = conv + 1; 
      string conn = "conn string"; 
      string sqlQuery = "UPDATE TableName SET Total [email protected]"; 
      using (SqlConnection dataConnection = new SqlConnection(conn)) 
      { 
       using (SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection)) 
       { 
        dataCommand.Parameters.AddWithValue("Total", set); 
        dataConnection.Open(); 
        dataCommand.ExecuteNonQuery(); 
        dataConnection.Close(); 

       } 
      } 

     } 

我不知道爲什麼不工作,我需要一個在當前編輯行的細胞增加。

感謝

+0

您已經聲明和初始化'conv'卻無處使用。什麼是'stra',因爲它沒有在你的代碼中聲明或初始化? – 2012-04-09 19:06:20

+0

而且我的代碼是不工作的東西是錯誤的..但我不知道在哪裏,因爲我沒有得到任何錯誤,但沒有更新 – 2012-04-09 19:13:01

回答

0

基於你在這裏提供什麼,你永遠不會actaully添加任何

int set = stra + 1; 

dataCommand.Parameters.AddWithValue("Total", set); 

試試這個

int stra = stra + 1; 

dataCommand.Parameters.AddWithValue("Total", stra); 
+0

對不起再看看我的代碼!...代碼不工作的東西是錯誤..但我不知道在哪裏,因爲我沒有得到任何錯誤,但沒有更新 – 2012-04-09 19:12:31

+0

將它包裝在一個try語句中,並讓它捕獲任何異常,只是爲了驗證100%沒有任何錯誤http:// msdn .microsoft.com/en-us/library/0yd65esw.aspx – 2012-04-09 19:15:29

+0

不存在錯誤,但我確定我的代碼不正確。 – 2012-04-09 19:20:08

0
  • 你upding所有行,而不是由於您沒有提供密鑰,因此只有編輯過的密碼
  • 您應該使用e.NewValues檢索修正值

    string sqlQuery = "UPDATE TableName SET [email protected] WHERE [email protected]"; 
    using (SqlConnection dataConnection = new SqlConnection(conn)) 
    { 
        using (SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection)) 
        { 
         var total = (int)e.NewValues["Total"] + 1; 
         dataCommand.Parameters.AddWithValue("Total", total); 
         dataCommand.Parameters.AddWithValue("ID", (int)e.Keys["ID"].Value); 
         dataConnection.Open(); 
         dataCommand.ExecuteNonQuery(); 
        } 
    } 
    
+0

指定的轉換無效。 (var total =(int)e.NewValues [「Total」] + 1;)我也忘記提及列總數是隻讀的,它以0開頭。(現在我沒有寫任何代碼只讀單元格值爲1)僅用於測試。 – 2012-04-09 19:24:38

+0

而來自名爲Total的單元格的值永遠不會被編輯,因爲我將它設置爲只讀,並且需要增加代碼 – 2012-04-09 19:25:59

+0

那麼Total是什麼類型?你有沒有調試過e.NewValues'是否包含'Total'? – 2012-04-09 19:32:14

相關問題