Even though you have marked this as solved I would recommend a bit different approach.
Currently you execute a delete statement separately for each row. If the grid contains 100 rows to delete, you execute 100 separate SQL statement. This causes a lot of round-trips to the database and back and is both time and resource consuming.
Instead, why not gather all the keys inside the for each loop and then delete all the rows using a single statement using
IN
comparison.
Another thing is that you open and close the connection inside the loop. This causes two things:
- resource usage
- lack of transaction between row deletions
You should open the connection once, delete the rows, check that everything went smoothly and then close the connection
Third thing is that you're not using using blocks. They should be used in order to dispose resources properly.
What comes to the code suggestion, a pseudo-code would look like
for each grid row
store the id value in a list of strings
using connection
using command
sql = "DELETE FROM TableName WHERE ID IN (" & String.Join(", ", stringlist.ToArray) & ")
try
open connection
execute statement
close connection
catch
handle errors
An example delete statement would look like
DELETE FROM TableName WHERE ID IN (1, 5, 99, 12, 55)
For more information about utilizing the using blocks, transaction etc, have a look at
Properly executing database operations[
^]