Results 1 to 2 of 2

Thread: [02/03] Collection was modified; enumeration operation may not execute.

  1. #1

    Thread Starter
    Frenzied Member Asgorath's Avatar
    Join Date
    Sep 2004
    Location
    Saturn
    Posts
    2,036

    [02/03] Collection was modified; enumeration operation may not execute.

    Hi
    I got 2 datagrid and single column. Datagrid 1 contains 2 rows number 2 and 3. Datagrid2 contains 1, 2 and 3. I want to remove the duplicate numbers on datagrid2. The tables are unrelated so i would have to use cursors.

    VB Code:
    1. Try
    2.             Dim a As String
    3.             For i As Integer = 0 To ds1.Tables(0).Rows.Count - 1
    4.                 a = Me.DataGrid1.Item(i, 0).ToString.TrimEnd
    5.                 For Each row As DataRow In ds2.Tables(0).Rows
    6.                     ''Console.WriteLine(row.Item(0).ToString)
    7.  
    8.                     If row.Item(0).ToString = a Then
    9.  
    10.                         ds2.Tables(0).Rows.Remove(row)
    11.                     End If
    12.                 Next
    13.             Next
    14.         Catch ex As Exception
    15.             Console.WriteLine(ex.Message)
    16.         End Try
    17.         Me.DataGrid2.DataSource = ds2.Tables(0)

    I get the exception Collection was modified; enumeration operation may not execute. Any suggestions , thanks.
    Jorge
    "The dark side clouds everything. Impossible to see the future is."

  2. #2
    Hyperactive Member Bananafish's Avatar
    Join Date
    Jan 2001
    Posts
    394

    Re: [02/03] Collection was modified; enumeration operation may not execute.

    I would suggest you need to iterate through the rows backwards, as you are removing columns and that will change the boundries of your For Each Rows loop.

    ie

    Instead of
    VB Code:
    1. For Each row As DataRow In ds2.Tables(0).Rows
    2.                     ''Console.WriteLine(row.Item(0).ToString)
    3.  
    4.                     If row.Item(0).ToString = a Then
    5.  
    6.                         ds2.Tables(0).Rows.Remove(row)
    7.                     End If
    8.                 Next

    Use
    VB Code:
    1. For intRow As Integer =  ds2.Tables(0).Rows.Count - 1 to 0 Step - 1
    2.    Next

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width