2013-04-24 59 views
2

我試圖刪除網格視圖中的行。對於那個我在下面的rowdeleting事件中寫代碼。無法在網格視圖中的rowdeleting事件中獲取單元值

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
     { 
      string UserId; 
      SqlTransaction tran; 

      using (con = new SqlConnection()) 
      { 

       con.ConnectionString = ConfigurationManager.ConnectionStrings["EMASFBAConnectionString"].ConnectionString; 
       cmd = new SqlCommand(); 
       cmd.Connection = con; 
       con.Open(); 
       tran = con.BeginTransaction(); 
       TableCell cell = GridView1.Rows[e.RowIndex].Cells[1]; 
       string username = cell.Text; 
       cmd.Transaction = tran; 

       cmd.CommandText = "Delete from aspnet_Users where UserName='" + username + "'"; 
       UserId = cmd.ExecuteScalar().ToString(); 

       if (UserId.Length!=0) 
       { 
        //delete user from membership table. 
        errorLabel.Text = "User is ready to delete"; 

       } 
       tran.Commit(); 
       con.Close(); 
      } 
     } 

當調試單元值即將爲空。我在這裏犯了什麼錯誤? 此網格視圖在每行前面都有編輯和刪除按鈕。 我嘗試使用Cells[0],Cells[2],但只給出空值。任何人都可以給我解決方案嗎?

+0

你確定你已經編寫了代碼刪除,如在「commandtext」你有寫選擇命令????? – 2013-04-24 06:31:51

+0

多數民衆贊成。我剛剛從我之前的塊中複製了它的文本。但是這裏的問題是細胞價值不會到來。它是作爲空值而來的。現在查看已編輯的問題。 – Mihir 2013-04-24 06:34:37

回答

3

終於拿到答案。如果我嘗試獲取表格單元格的值,它不會給出正確的值。所以我嘗試這樣,

GridViewRow row = GridView1.Rows[e.RowIndex]; 
Label usernamelable = (Label)row.FindControl("lblUserNameValue"); 
string username = usernamelable.Text; 

這對我來說很好。我指的是GridView中的標籤控件並獲取值。

+0

在寫完相同的答案之前,您已經掌握了它,如果您正在使用ItemTemplate行,那麼最好通過FindControl()方法獲取值 – 2013-04-24 08:36:43

3

喜在GridView限定datakeys和使用此方法

string UserID = GridView1.DataKeys[e.RowIndex].Value.ToString(); 

,然後在此基礎上的ID刪除該行。

cmd.CommandText = "Delete from aspnet_Users where UserID=" + UserID; 

後打電話給你的數據綁定方法到GridView與更新後的記錄綁定

爲的DataKeyNames請使用此

 <asp:gridview datakeynames="UserID" 
     runat="server"> 
+0

如何給'DataKeys'? – Mihir 2013-04-24 06:50:02

+0

其真的很簡單,你可以將其設置爲HTML: 2013-04-24 06:57:50

1

試試下面的代碼:

var empId = Convert.ToInt32(this.gvDetails.DataKeys[e.RowIndex].Values["EmpId"].ToString()); 
+0

對我來說這是正確的方法獲取特定密鑰的價值。 – Mario 2017-10-06 12:23:48

相關問題