Wednesday, March 31, 2010

Items collection cannot be modified when the DataSource property is set

I received the following error "Items collection cannot be modified when the DataSource property is set"  when populating the combo box with data table.

Reason:

The Items.Clear method was called while the combo box's data source was assigned.

Solution:


Need to set the combo box's data source to nothing before calling Items.Clear method
 
The following sample code explains this scenario clearly.
 
Private Sub populateProducts()
Dim SQLAdapter As SqlDataAdapter = Nothing

Try

 
Dim strSQl As String = "SELECT ID, ProdName  FROM  tblProducts"
SQLAdapter = New SqlDataAdapter(strSQl, SConnectionString)

Dim dt As New DataTable

SQLAdapter.Fill(dt)

cmbProducts.DataSource = Nothing // Need to set the data source nothing
                                                           // Comment this line to reproduce the error

cmbProducts.Items.Clear()

cmbProducts.DataSource = dt


cmbProducts.DisplayMember = "ProdName"


cmbProducts.ValueMember = "ID"

Catch ex As Exception


lblStatus.Text = ex.Message
End Try
End Sub

1 comment: