Click here to Skip to main content
15,902,198 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello everyone.
I have an Access table "Print" that I load into my program using dataGridView6.
I want to remove all selected rows in dataGridView6 and Assess table with one click.
I am asking for your help. Thank you.


What I have tried:

private void Button1_Click(object sender, EventArgs e)
       {
           for (int i = 0; i < dataGridView6.SelectedRows.Count; i++)
           {
               string query = "Delete From Print Where Id=@id";
               cmd = new OleDbCommand(query, con);
               cmd.Parameters.AddWithValue("@id", dataGridView6.SelectedRows[i].Cells[0].Value);
               con.Open();
               cmd.ExecuteNonQuery();
               con.Close();
           }
       }
Posted
Updated 19-Jan-23 8:48am
v2

1 solution

Your code is creating a multitude of objects it doesn't need to create. Get the query setup and parameter out of the loop and setup the connection so it only has to be opened once. You also have to dispose your connection object when you're done with it. That is easily done with a using statement:
C#
using (OleDbConnection con = new OldDbConnection(...connection string...))
{
    string query = "DELETE FROM Print WHERE Id=@id";
    OleDbCommand cmd = new OldDbCommand(query, con);
    OleDbParameter idParam = new OleDbParameter("@id", OleDbType.Integer);    // Or whatever your Id type is...
    cmd.Parameters.Add(idParam);

    con.Open();

    for (int i = 0; i < dataGridView6.SelectedRows.Count; i++)
    {
        idParam.Value = dataGridView6.SelectedRows[i].Cells[0].Value;
        cmd.ExecuteNonQuery();
    }
}
 
Share this answer
 
Comments
Member 10410972 19-Jan-23 16:47pm    
Thank you very much, it works fine for me. Best regards.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900