The following example read from a database table to populate a BindingSource which becomes the DataSource of a DataGridView. Now this data does not have to come from a database, I did it this way to keep things simple.
The delete operation is chunked into 20 at a time using WHERE IN. Let's say that in one chunk no all serial values exists the operation is performed on those that do exists.
Coded with .NET Core 7
Container for storing data
public class Container
{
public string Serial { get; set; }
public DateTime SomeDate { get; set; }
}
Data class
public class DataOperations
{
private const string ConnectionString =
"Data Source=.\\SQLEXPRESS;Initial Catalog=ForumExample;Integrated Security=True;Encrypt=False";
public static List<Container> Read()
{
List<Container> list = new List<Container>();
using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand()
{
Connection = cn,
CommandText = "SELECT Serial,SomeDate FROM dbo.Demo1"
};
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new Container()
{
Serial = reader.GetString(0),
SomeDate = reader.GetDateTime(1)
});
}
return list;
}
public static bool DeleteRecords(List<string> statements)
{
using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand() { Connection = cn };
cn.Open();
try
{
foreach (var statement in statements)
{
cmd.CommandText = statement;
cmd.ExecuteNonQuery();
}
return true;
}
catch (Exception)
{
return false;
}
}
}
Form code
public partial class Form1 : Form
{
private readonly BindingSource _bindingSource = new ();
public Form1()
{
InitializeComponent();
_bindingSource.DataSource = DataOperations.Read();
dataGridView1.DataSource = _bindingSource;
}
private void DeleteButton_Click(object sender, EventArgs e)
{
var list = ((List<Container>)_bindingSource.DataSource).Select(x => $"'{x.Serial}'").Chunk(20).ToList();
var deleteStatements = new List<string>();
foreach (var serialLArray in list)
{
deleteStatements.Add($"DELETE FROM [Demo1] WHERE [Serial] IN ({string.Join(",", serialLArray)})");
}
if (DataOperations.DeleteRecords(deleteStatements))
{
_bindingSource.DataSource = null;
DeleteButton.Enabled = false;
}
else
{
MessageBox.Show("Failed");
}
}
}