[英]Delete button only deleted first row in gridview
I added a delete button in my GridView. 我在GridView中添加了删除按钮。 But the problem is it always deletes the first row.
但是问题在于它总是删除第一行。
For instance, if I am deleting the the second or the third row, the data in the first row will be deleted. 例如,如果我要删除第二行或第三行,则第一行中的数据将被删除。 I just want the button to delete the row beside it:
我只希望按钮删除它旁边的行:
public void bindgrid()
{
SqlConnection conn = new SqlConnection("cnString");
SqlCommand cmd = new SqlCommand("select Id,Name, from myTable ", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select Id,Name, from myTable", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
gridview1.DataSource = ds.Tables[0].DefaultView;
gridview1.DataBind();
}
protected void gdview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = int.Parse(gridview1.DataKeys[0].Value.ToString());
SqlConnection conn = new SqlConnection("cnString");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.DeleteCommand = new SqlCommand("delete from myTable where Id=" + userid , conn);
da.DeleteCommand.ExecuteNonQuery();
conn.Close();
bindgrid();
}
You should pass the current row index instead of gridview1.DataKeys[0]
您应该传递当前行索引而不是
gridview1.DataKeys[0]
protected void gdview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = int.Parse(gridview1.DataKeys[e.RowIndex].Value.ToString());
SqlConnection conn = new SqlConnection("cnString");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.DeleteCommand = new SqlCommand("delete from myTable where Id=" + userid , conn);
da.DeleteCommand.ExecuteNonQuery();
conn.Close();
bindgrid();
}
The problem is in below line 问题在下面的行中
int userid = int.Parse(gridview1.DataKeys[0].Value.ToString());
You are always getting the userid of the first row by using [0] 您总是通过使用[0]获取第一行的用户ID。
Get the appropriate value from "e" and pass that. 从“ e”获取适当的值并将其传递。
e.RowIndex
something llike this 像这样的东西
GridViewRow row = gridview1.Rows[e.RowIndex];
int userid = int.Parse(row[0].Value.ToString());
Replace this line 替换此行
int userid = int.Parse(gridview1.DataKeys[0].Value.ToString());
to this 对此
int userid = int.Parse(gridview1.DataKeys[e.RowIndex].Value.ToString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.