在Visual Basic中循环使用DataTable时出错

时间:2012-09-08 21:55:18

标签: vb.net datatable

我在下面编写的代码将正确迭代循环。它根据条件测试正确的行,添加到“辅助”DataTable并按照预期从“master”中删除。但是,在循环的第二次迭代中,我得到以下错误:

Collection was modified; enumeration operation might not execute.

以下是我正在使用的代码

            For Each row As DataRow In tblAgencyEdInfo.Rows
                Dim rDate As DateTime = row.Item("ExpirationDate")

                If rDate < DateTime.Now Then
                    tblExpEdInfo.ImportRow(row)
                    tblAgencyEdInfo.Rows.Remove(row)
                End If
            Next row

2 个答案:

答案 0 :(得分:2)

您无法在枚举期间修改集合。这意味着您无法添加或删除项目。在这种情况下,您希望从For Each循环中的DataTable中删除DataRow。

解决方案要么

  1. 使用For-Loop并向后迭代项目,通过索引删除行或
  2. 使用另一个集合(f.e.a List(Of DataRow))并在For Each中添加要删除的匹配行。之后,您只需要迭代此列表并致电tblAgencyEdInfo.Rows.Remove(rowToRemove)
  3. 例如:

    Dim rowsToRemove = New List(Of DataRow)
    For Each row As DataRow In tblAgencyEdInfo.Rows
        Dim rDate As DateTime = row.Item("ExpirationDate")
        If rDate < DateTime.Now Then
            rowsToRemove.Add(row)
        End If
    Next row
    
    For Each rowToRemove As DataRow In rowsToRemove 
        tblExpEdInfo.ImportRow(row)
        tblAgencyEdInfo.Rows.Remove(row)
    Next rowToRemove 
    

答案 1 :(得分:0)

以上情况属实,使用时无法改变。

        ' distinct
        Dim distinctTable As DataTable = tblProductsForDisplay.DefaultView.ToTable(True)
        ' get all bundles that contain products in bundles - GetBundleDataByOLLID
        For Each row As DataRow In distinctTable.Rows
            Dim myOLLCourseID As Integer = row.Item("OLLCourseID")
            tblProductsForDisplay.Merge(tblBundles(myOLLCourseID))
        Next

所以我在这里做的是将数据移动到另一个副本,使用Distinct&#34; ToTable(True)&#34;过滤它甚至更窄/清理。

然后使用原始数据表合并项目,添加到原始项目,同时循环访问我的副本。我原来现在有所有项目和新项目。你的logiv可能以不同的方式改变原始,但我只是想通过例子来展示。

RA

相关问题