2013-04-24 65 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

相关问题