0

I have a DataGridView that is bound to a DataTable which in turn is filled from a database. In this grid, I have a couple of DataGridViewComboBoxColumns with data bound to ArrayLists like so:

Dim ComboBoxData As ArrayList = New ArrayList(New String() {"", 
                                                            "Default", 
                                                            "User-set"})
Dim ComboBoxBS As BindingSource = New BindingSource
ComboBoxBS.DataSource = ComboBoxData
SomeDataGridViewComboBoxColumn.DataSource = ComboBoxBS

I want to allow that the fields in the DataTable may have other values than those defined in the ComboBoxData. This I have done by handling the DataError event and adding the missing values to the ComboBox:

Private Sub grid_DataError(ByVal sender As System.Object, 
                           ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs
                           ) Handles grid.DataError
    If TypeOf grid.Columns(e.ColumnIndex) Is DataGridViewComboBoxColumn Then
        Dim value = grid.Rows(e.RowIndex).Cell(e.ColumnIndex).Value
        Dim cboCol As DataGridViewComboBoxColumn = CType(grdDataGrid2.Columns(e.ColumnIndex), DataGridViewComboBoxColumn)
        Dim bs As BindingSource = CType(cboCol.DataSource, BindingSource)
        If Not bs.Contains(value) Then
            bs.Add(value)
            bs.Position = bs.IndexOf(value)
        End If
        e.Cancel = False
        Return
    End If
End Sub

This works for all rows except the first. By debugging I've confirmed that the DataError event indeed doesn't fire for the first row. There is however a red exclamation mark in the row header claiming "Data type mismatch in criteria expression".

Why doesn't the first row behave as the rest? Please also suggest better approaches to this problem.

joharei
  • 578
  • 1
  • 5
  • 22

1 Answers1

0

Try referencing the DataGridViewComboBoxCell rather than the DataGridViewComboBoxColumn. In my own situation, with a comboboxcolumn bound to a datatable, I was able to get it updating the first row to the appropriate new value only once I referenced the cell. You may just need to reassign the value as I did in the last line of code below.

Dim comboCell As DataGridViewComboBoxCell = DirectCast(targetGrid.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewComboBoxCell)
Dim comboData As DataTable = DirectCast(comboCell.DataSource, DataTable)
Dim oRow As DataRowView = comboData.DefaultView.AddNew()
oRow(oComboCol.DataPropertyName) = targetValue
oRow.EndEdit()
comboData.AcceptChanges()
comboCell.Value = targetValue