The error "Collection was modified; enumeration operation may not execute" is often being experienced by the users.
Whenever the operation of addition of items or deletion of items happening in the list of items using for each loop it happens.
This is because foreach statement uses an Enumerator, which is a little object
optimized to move through a collection which doesn't change.
So if we remove the items from the Enumerator, You are changing the contents of the list during enumeration which is the no-no being reported.
The better way to handle would be to avoid changing such collections.
Consider the following scenario:
We need to remove rows from the DataGridview whose First Field Contains the Value "NA"
Wrong Code:
DataTable dt = (DataTable)GridView1.DataSource;
foreach (DataRow dr in dt.Rows)
{
string dtitem = dr["Item Description"].ToString();
if (dtitem == "NA")
{
dr.Delete();
}
}
dt.AcceptChanges();
gridivew1.DataSource = dt;
gridivew1.DataBind();
We will get the error "Collection was modified; enumeration operation may not execute"
Solution
Here is the work around.
for(int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows(i);
string dtitem = dr["Item Description"].ToString();
if (dtitem == item)
{
dt.Rows.Remove(i);
}
}
The trick is in this For Loop only. for(int i = dt.Rows.Count - 1; i >= 0; i--)
Because if we start the index From 0 To dt.Rows.Count - 1
as soon as we remove the rows it cannot recognize the index and will throw "Index Outbound of exception
For Example,
the data table contains 4 Rows.
Assume we start From 0 To 3 and if we remove row 2, the data table contains only 3 rows and will not contain the index 3.
No comments:
Post a Comment