2011-12-29 73 views
-1

事情是這樣的:在我的應用程序的形式加載我創建一個後臺工作綁定集合(從數據庫記錄填寫數據集中)在我的控制。但問題是當我更新數據庫上的記錄時,如果我再次運行此過程,則會引發錯誤。VBNet錯誤:收集已修改;枚舉操作可能不會執行

If xControl.InvokeRequired Then 
     Dim MyDelegate As New InitializeDataBinding_Delegate(AddressOf InitializeDataBinding) 
     Invoke(MyDelegate, New Object() {xControl, xQuery, xPrimaryKey}) ' ERROR HERE SAYING: Collection was modified; enumeration operation may not execute. 
    Else 
     Using ds As DataSet = New DataSet() 
      Using dbAdapter As MySqlDataAdapter = New MySqlDataAdapter(xQuery, ConnectionClass.ConnectionString) 
       dbAdapter.Fill(ds) 
      End Using 

      Dim dvm As DataViewManager = New DataViewManager(ds) 
      Dim iDataList As DataView = dvm.CreateDataView(ds.Tables(0)) 
      For Each iBind As Binding In xControl.DataBindings 
       xControl.DataBindings.Remove(iBind) 
      Next 
      xControl.DataBindings.Add("EditValue", iDataList, xPrimaryKey) 
      xControl.Properties.DataSource = iDataList 
      xControl.EditValue = Nothing 
      txtStatus.Text = "Ready" 
     End Using 
    End If 

回答

0

解決加入:

xControl.DataBindings.Clear()

If xControl.InvokeRequired Then 
    Dim MyDelegate As New InitializeDataBinding_Delegate(AddressOf InitializeDataBinding) 
    Invoke(MyDelegate, New Object() {xControl, xQuery, xPrimaryKey}) ' ERROR HERE SAYING: Collection was modified; enumeration operation may not execute. 
Else 
    Using ds As DataSet = New DataSet() 
     Using dbAdapter As MySqlDataAdapter = New MySqlDataAdapter(xQuery, ConnectionClass.ConnectionString) 
      dbAdapter.Fill(ds) 
     End Using 

     xControl.DataBindings.Clear() 'HERE 

     Dim dvm As DataViewManager = New DataViewManager(ds) 
     Dim iDataList As DataView = dvm.CreateDataView(ds.Tables(0)) 
     For Each iBind As Binding In xControl.DataBindings 
      xControl.DataBindings.Remove(iBind) 
     Next 
     xControl.DataBindings.Add("EditValue", iDataList, xPrimaryKey) 
     xControl.Properties.DataSource = iDataList 
     xControl.EditValue = Nothing 
     txtStatus.Text = "Ready" 
    End Using 
End If 
4

您必須在使用For Each迭代時避免集合中的更新。使用簡單的For循環而不是For Each。

+0

問題解決了,我只在循環前添加了這個代碼xControl.DataBindings.Clear() – 2011-12-29 02:22:35

2

不能使用For Each循環從措辭或KeyValuePair刪除項目,但你可以使用普通的for循環,拿到鑰匙並使用該鍵從列表中刪除該項目。

 For i As Integer = 0 To oDictionary.Count - 1 
     Dim sKey = m_oDictionary.ElementAt(i).Key 
     m_oDictionary.Remove(sKey) 
     Next 
0
 Dim index As Integer = 0 
opnieuw: 
     For Each F In openbestand.file 
      If F.Contains("~$") Then 
       openbestand.file.Remove(openbestand.file(index)) 
       openbestand.path.Remove(openbestand.path(index)) 
       GoTo opnieuw 
      Else 
       index = (index + 1) 
      End If 
    Next 
0

如果你要使用一個循環,你需要確保該指數小於計數,因爲計數減少每一個關鍵元素被刪除時間:

Dim i As Integer 

For i = 0 To dictionary1.Count - 1 
    If i <= dictionary1.Count - 1 Then 
     Dim sKey = dictionary1.ElementAt(i).Key 
     dictionary1.Remove(sKey) 
    End If 
Next