这是我的代码,我想在单击该行的 DELETE 按钮时删除该行,同时数据库也应该得到更新。
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Delete"))
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvDetails.Rows[index];
string productID = gvDetails.DataKeys[index].Value.ToString();
string productName = row.Cells[1].Text;
this.RemoveProduct(productID, productName);
}
}
public void RemoveProduct(string productID, string productName)
{
DataRow dr;
SQLConnection objcon;
SqlDataAdapter objadp;
objcon=new SqlConnection("Connecting string");
try
{
objcon.Open();
DataSet ds = new DataSet();
objadp = new SqlDataAdapter("Select *from Bus_Table", objcon);
objadp.Fill(ds, "Bus_Table");
objadp.DeleteCommand = objcon.CreateCommand();
objadp.DeleteCommand.CommandText = "DELETE from Bus_Table where B_ID=" +int.Parse(productID);
DataTable objtable = new DataTable();
ds.Tables.Add(objtable);
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["B_ID"].Equals(productID))
{
DataRow objrow = dr;
objrow.Delete();
objadp.Update(ds, "Bus_Table");
ds.AcceptChanges();
Response.Write("Bus Deleted");
break;
}
}
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
finally
{
objcon.Close();
}
}
当我编译此代码时出现错误:
“除非指定了 DeleteCommand,否则数据源 'SqlDataSource1'(我的数据源)不支持删除”。
当我设置断点时,我注意到RemoveProduct(string productID, string productName)
没有被调用,gvDetails_RowCommand()
但条目也被删除。