我在GridView中添加了一个删除按钮。但问题是它总是删除第一行。
例如,如果我删除第二行或第三行,将删除第一行中的数据。我只想按下按钮删除它旁边的行:
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();
}
答案 0 :(得分:3)
您应该传递当前行索引而不是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();
}
答案 1 :(得分:0)
问题出在以下行
int userid = int.Parse(gridview1.DataKeys[0].Value.ToString());
您始终使用[0]
获取第一行的用户ID从“e”获取适当的值并传递给它。
e.RowIndex
答案 2 :(得分:0)
喜欢这个
的东西GridViewRow row = gridview1.Rows[e.RowIndex];
int userid = int.Parse(row[0].Value.ToString());
答案 3 :(得分:0)
替换此行
int userid = int.Parse(gridview1.DataKeys[0].Value.ToString());
到这个
int userid = int.Parse(gridview1.DataKeys[e.RowIndex].Value.ToString());