1.gridview控件编辑列,添加TemplateField,将HeadText属性改为“删除”,即在gridview控件中添加了新的删除行;
2.选中gridview控件,右键属性,单击闪电(事件)图标,在RowDeleting后面输入GridView1_RowDeleting,双击RowDeleting生成删除事件;
3.代码部分
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string strCon = "server=127.0.0.1;database=SMSstudent;user id=sa;pwd=sa";
using (SqlConnection conn = new SqlConnection(strCon))
{
string sql = "delete from Bu where buid='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
<span style="color:#ff0000;"> SqlDataSource1.DeleteCommand = sql;</span>
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
}
有些时候会出现数据已经删除,但是还是报上述错误,原因就是因为少了上面代码中的红色部分代码。