Search code examples
asp.netgridviewvisual-studio-2008sql-delete

Deleting a Gridview row when the DELETE button is pressed in the respective rows


This is my code I want to delete the row when that row's DELETE button is clicked and at the same time the database should also get updated.

    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();
    }
}

When I am compiling this code am getting an error:

"Deleting is not supported by data source 'SqlDataSource1'(my data source) unless DeleteCommand is specified".

When I put a breakpoint I noticed that the RemoveProduct(string productID, string productName) is not getting called from gvDetails_RowCommand() but the entry gets deleted too.


Solution

  • take a look at these articles, it would explain in detail on how to delete single/multiple rows from gridview. http://technico.qnownow.com/2012/06/15/how-to-delete-multiple-rows-from-gridview-with-checkboxes/ http://technico.qnownow.com/2012/06/14/how-to-delete-a-row-from-gridview-with-client-side-confirmation/