John Woo John Woo - 2 months ago 14
Vb.net Question

VBNet Error: Collection was modified; enumeration operation may not execute

This is what happened: on the form load of my application i created a background worker to bind collection (records from database filled in the dataset) on my control. but the problem is when the i updated the records on the database it throws an error if i run this procedure again.

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

Answer

Solved by adding:

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