You cannot modify collection while enumerating it using Enumerator, which is happening behind the scene of the foreach
statement (MDSN link).
One possible way to solve this problem is to collect rows to be deleted in the first enumeration and than remove them in the separate loop like this:
var rowsToDelete = new List();
foreach (DataRow row in dataTable.Rows)
{
temp = row[0].ToString();
foreach (DataRow rows in dataTable.Rows)
{
if (temp == rows[0].ToString())
{
tempdatatable.Rows.Add(row[0],row[1]);
rowsToDelete.Add(rows);
}
tempdatatable.DefaultView.Sort = "gscitations DESC";
dataGridView1.DataSource = tempdatatable;
}
}
rowsToDelete.ForEach( x => dataTable.Rows.Remove(x) );
You can also replace foreach
loop with for
, but you need to do extra work properly handling the current index while deleting the elements.