Dec 21, 2009

Items collection cannot be modified when the DataSource property is set

You get this error 'Items collection cannot be modified when the DataSource property is set' when you try to add/ append items to a already data bound control say for example a combo box in a winform application.

The solution is to insert the item when you are creating the datasource say for example in the following example, insert the 'select' item before binding the combo box with the data table. Many a times it is good to prepare the data source in advance and make any changes required in it thereafter only use it for binding purposes.

Example code:
        Dim dt As New DataTable()
        dt.Columns.Add("Column1")

        Dim dr As DataRow = dt.NewRow()
        dr("Column1") = "data1"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("Column1") = "-select-"
        dt.Rows.InsertAt(dr, 0)

        ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
        ComboBox1.ValueMember = "Column1"
        ComboBox1.DisplayMember = "Column1"
        ComboBox1.DataSource = dt

No comments:

Post a Comment