这就是发生的事情:在我的应用程序的表单加载中,我创建了一个后台工作程序来绑定我的控件上的集合(来自数据集中填充的数据库的记录)。但问题是当我更新数据库上的记录时,如果我再次运行此程序,则会抛出错误。
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 :(得分:4)
使用For Each迭代时,必须避免集合中的更新。使用简单的For循环而不是For Each。
答案 1 :(得分:2)
您不能使用For Each循环从diction或KeyValuePair中删除项目,但您可以使用常规for循环,获取密钥并使用密钥从列表中删除该项目。
For i As Integer = 0 To oDictionary.Count - 1
Dim sKey = m_oDictionary.ElementAt(i).Key
m_oDictionary.Remove(sKey)
Next
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分:0)
如果要使用循环,则需要确保索引小于Count,因为每次删除关键元素时计数都会减少:
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