What you are doing is removing the selected rows from the DataGridView
only.
You are not making any database call to delete the rows.
I assume you are using Microsoft SQL server.
In that case you will need to get the something that uniquely identifies product. For example Product Id.
Assuming you've got your ProductId
column from the database bound to some column in DataGridView
.
Your code should be like below.
//string variable to capture product Ids for selected products
System.Text.StringBuilder productIds = new System.Text.StringBuilder(string.empty);
for (int i = 0; i < Products.Rows.Count; i++)
{
DataGridViewRow dr = Products.Rows[i];
if (dr.Selected == true)
{
Products.Rows.RemoveAt(i);
productIds.Append(productIds.length > 0 ? "," + Convert.ToString(dr["ProductId"]) : Convert.ToString(dr["ProductId"]));
}
}
DeleteProducts(productIds.ToString());
Now your DeleteProducts
method should be as below.
private int DeleteProducts(string productIds)
{
int recordsDeleted = 0;
using (SqlConnection conn = new SqlConnection("Your connection string here"))
{
try
{
using (SqlCommand cmd = new SqlCommand("Your SQL Stored Procedure name here", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramProductIds = new SqlParameter("@productIds", varchar(2000));
paramProductIds.Value = productIds;
cmd.Parameters.Add(paramProductIds);
conn.Open();
recordsDeleted = cmd.ExecuteNonQuery();
}
}
finally { conn.Close(); }
}
return recordsDeleted;
}
And your stored procedure should be as below (Assuming MS SQL Server).
CREATE PROCEDURE DeleteProducts
@productIds VARCHAR(2000)
AS
BEGIN
DELETE FROM Products WHERE ProductId IN (SELECT item FROM dbo.Split(',', @productIds))
END