I am trying to loop through a DataTable
and during that loop I am comparing each row to another DatabTable
and then if the record matches remove the row. The resulting DataTable
then gets put into a DataGridView
.
However I am getting the following error:
System.InvalidOperationException: 'Collection was modified; enumeration operation might not execute.'
Im not 100% sure but I think its because I am modifying the Table that is being looped through? But if that is the case how do i then remove the rows that are duplicates?
My code is as follows:
foreach (DataRow dr in dtM1.Rows)
{
int matchCount = 0;
string id = dr["cmoOrganizationID"].ToString();
foreach (DataRow dr2 in dtSQLite.Rows)
{
//MessageBox.Show(id " " dr2["sSupplierID"].ToString());
if (dr2["sSupplierID"].ToString() == id)
{
matchCount ;
}
}
if (matchCount > 0)
{
dtM1.Rows.Remove(dr);
MessageBox.Show("Item to remove" id);
}
}
dgv.DataSource = dtM1;
CodePudding user response:
At dtM1.Rows.Remove(dr)
you remove a row from the DataTable
that you are currently enumerating. That breaks the loop, hence you get the exception. You cannot modify the underlying collection during enumeration.
One solution is to fill a list and remove the rows afterwards:
var removeRows = new List<DataRow>(); // before loop
// in the loop ...
if (matchCount > 0)
{
removeRows.Add(dr);
MessageBox.Show("Item to remove" id); // don't show MessageBoxes in a loop
}
// rest of loop ...
and now remove it after the loop:
removeRows.ForEach(dtM1.Rows.Remove);