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");
}
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, eg:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.