开发者

Collection was modified; enumeration operation might not execute [duplicate]

This question already has answers here: How do I lo开发者_JS百科op through items in a list box and then remove those item? (8 answers) Closed 9 years ago.

I faced a problem with a DataTable. When I run to client it throws an Exception and mentions the "in" in foreach.

Collection was modified; enumeration operation might not execute.

This is the code:

foreach (DataRow dr in stStatusTable.Rows)
{
    if (Convert.ToInt32(dr["st_id"]) == stStatus.st_id)
    {
        dr["st_id"] = Convert.ToInt32(dr["st_id"]) + 1;
        dr.AcceptChanges();

    }
    else
    {

        stStatusTable.Rows.Add(stStatus.st_id, stStatus.st_name, stStatus.RTime, stStatus.Total_Mark, stStatus.Completed);
    }
}

How can I solve this?


Use a for-loop instead of an foreach loop.

However, be careful with the index when adding / removing items.


Becouse you are adding rows at the same time you are enumerating them..

You should add the rows to a second clean datatable, and after the loop, copy the rows from the new datatable to the original one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜