0

Below is my code which am calling and am getting below exception. Collection was modified; enumeration operation might not execute.

In this code am checking if dataset contains tb_error table name and then checking the row count. If rowcount> 1 , insert into db. after that i want to clear that table and after that i need to clear other view also. Please help me where to modify my code.

    if (MainClass.OutputDataset.Tables.Contains(tb_error.TableName))
         {
             foreach (DataRow drErr in MainClass.OutputDataset.Tables[tb_error.TableName].Rows)
             {
                 //insert into DB
             }
         }

        if (MainClass.OutputDataset != null && MainClass.OutputDataset.Tables["tb_error"].Rows.Count > 0)
        {
            MainClass.OutputDataset.Tables["tb_error"].Clear();
        }

        MainClass.dsinput.Tables.Remove("BSData_VW");               
        }
A G
  • 21,087
  • 11
  • 87
  • 112

2 Answers2

0

This happens because the underlying collection has since had items added or removed, which invalidates the loop.

You can get around this by taking a snapshot, e.g.:

foreach (DataRow drErr in MainClass.OutputDataset.Tables[tb_error.TableName].Rows.ToList())
{
   //insert into DB
}

The key is the .ToList() call at the end, which means the foreach loop only operates on Rows as it is at the point-in-time.

Clint
  • 6,133
  • 2
  • 27
  • 48
-1

When you get an error like that, you pretty much have to abandon using foreach and come up with some other looping mechanism. You can try using a for statement or rolling your own with a variable and a while statement.

Jim
  • 2,034
  • 1
  • 22
  • 43