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 Responses to Items collection cannot be modified when the DataSource property is set

  1. Anonymous Says:
  2. thank a lot, worked for me........

     

Post a Comment