Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am trying to loop through a DataTable to find each row where the "AccountNo" is equal to a number that is passed in.

I am getting the following error now:

Collection was modified; enumeration operation might not execute.


The code has errored on this loop:

VB
For Each DataRow In dt.Rows

            RowNumber = RowNumber + 1

            If DataRow("AccountNo").ToString() = CustomerIDForHistory Then

                Dim output As String = DataRow.ToString.ElementAt(RowNumber)

                dt.Rows.Add(output)

            End If
        Next



Thanks Glen
Posted

If you really need to add items inside the loop then you should (properly) use another kind of loop (for instance a for, or a while, depending on your needs) to iterate on the items of the DataTable collection, e.g.

C#
// this is most likely what you want to do, that is: NOT iterate on the newly inserted items
int COUNT = dt.Rows.Count;
for (int r = 0; r<COUNT; ++r)
{
  DataRow dr = dr.Rows[r];
  //...
}
 
Share this answer
 
v3
Comments
Glen Childs 15-Jan-14 9:52am    
Thanks that has solved the error, now I am getting a slightly different error... No default member found for type 'DataColumn'. Errors on the IF statement

Dim COUNT As Integer = dt.Rows.Count

For Each DataColumn In dt.Columns

For r As Integer = 0 To COUNT - 1

If DataColumn("AccountNo") = FrmSearch.txtCustID1.Text Then

Dim output As String = DataColumn.ToString().ElementAt(r)

dtValue.Rows.Add(output)

End If
Next
Next
You can not change the Collection you currently loop through !

so adding a value to dt.Rows, while you run a for each on dt.Rows.. throws that error

greets
 
Share this answer
 
The right way and also easiest to parse or loop a dictionary is to get its keys in a List and then loop through the dictionary using this key-list.

C#
List keyList = new List<int>(Dictionary.Keys);foreach (key in keys)
{
  // Now we can perform any modification wh values of dictionary.
  Dictionary[key] = Dictionary[key] - 1;
}</int>


Here is a detail blogpost about this: Example Here
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900