VBNet错误:集合已被修改;枚举操作可能无法执行

Joh*_*Woo 0 vb.net data-binding autocomplete backgroundworker

这就是发生的事情:在我的应用程序的表单加载中,我创建了一个后台工作器来绑定控件上的集合(数据库中记录填充到数据集中的记录)。但是问题是当我更新数据库上的记录时,如果我再次运行此过程,则会引发错误。

    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
Run Code Online (Sandbox Code Playgroud)

ada*_*ost 5

使用For Each进行迭代时,必须避免集合中的更新。使用简单的For循环,而不是For Each。