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 DataGridViewComboBoxColumn
s with data bound to ArrayList
s 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.