Search code examples
asp.netgridviewcheckboxsql-delete

How to delete multiple rows in a gridview using a checkbox?


I have a gridview with a checkbox in it and I'm trying to do a multiple delete using this code:

    protected void deleteUsers(object sender, EventArgs e) //deleting the selected users
{
    foreach (GridViewRow row in clientGrid.Rows) 
    {
        CheckBox selectBox = (CheckBox)row.FindControl("deleteUser");

        if (selectBox != null && selectBox.Checked) 
        {
            string bank, customerId, tMain, tSub;

            bank = bankName.InnerText;
            tMain = bank + "_main";
            tSub = bank + "_sub";

            customerId = Convert.ToString(clientGrid.DataKeys[row.RowIndex].Value);

            deleteSelected(tMain, tSub, customerId).ExecuteNonQuery();

            clientGrid.DataSource = getAllClients();
            clientGrid.DataBind();
        }
    }
}

and here is the sqlCommand:

    protected SqlCommand deleteSelected (string Tmain, string Tsub, string customerId) //the sql command for deleting
{
    string connection, commandSyntax;
    connection = ConfigurationManager.ConnectionStrings["localsqlserver"].ConnectionString;
    commandSyntax = "DELETE FROM [" + Tmain + "] FROM [" + Tsub + "] t1 " + 
                        "LEFT JOIN [" + Tmain + "] t2 ON t1.customer_id = t2.customer_id " +
                            "WHERE t1.customer_id = @customer_id" ;

    SqlConnection conn = new SqlConnection(connection);
    SqlCommand cmd = new SqlCommand(commandSyntax, conn);
    cmd.Parameters.AddWithValue("@customer_id", customerId);


    conn.Open();

    return cmd;
}

this works fine on deleting the only one checked user but if I check more than one I get this error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

I set the gridview datakey to the customer_id column which contains a guid.

I am using asp.net 4.0, what is the problem?


Solution

  • Your experiencing this because your rebinding your data grid inside of a foreach loop, causing the collection your currently iterating through to change in size, which in turn is throwing your index off.

    Instead try waiting until after you've performed all of your deletes to rebind your data grid.