I added a delete button in my 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]
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]
Get the appropriate value from "e" and pass that.
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.