2012-09-08 20 views
0

我在下面寫的代碼將正確地循環迭代循環。它根據條件測試正確的行,將其添加到「輔助」DataTable中,並按照它的要求從「主」中移除。然而,在該循環的第二次迭代我收到以下錯誤:在Visual Basic中通過DataTable循環的錯誤

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

枚舉過程中不能修改一個集合的代碼。這意味着你不能添加或刪除項目。在這種情況下,您想要從For Each循環中的DataTable中刪除DataRow。

的解決方法是,

  1. 使用For-Loop和向後遍歷項目,除去經指數或
  2. 使用另一個集合(FE一List(Of DataRow))行和添加要匹配的行刪除在For Each。然後你只需要遍歷這個列表,並呼籲tblAgencyEdInfo.Rows.Remove(rowToRemove)

例如:

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 
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 

因此,我在這裏做的移動數據表到另一個副本,使用另類「ToTable(真)」,以過濾它更窄/清理。

然後使用原始數據表合併項目,添加到原始項,同時循環遍歷我的副本。我原來的所有項目加上新的。您的logiv可能會以不同的方式改變原創,但我只是想通過示例來展示。

RA