我有DataGridView
绑定到DataTable
,而DataGridViewComboBoxColumn
又从数据库中填充。在这个网格中,我有几个ArrayList
s,数据绑定到Dim ComboBoxData As ArrayList = New ArrayList(New String() {"",
"Default",
"User-set"})
Dim ComboBoxBS As BindingSource = New BindingSource
ComboBoxBS.DataSource = ComboBoxData
SomeDataGridViewComboBoxColumn.DataSource = ComboBoxBS
,如下所示:
DataTable
我想允许ComboBoxData
中的字段可能具有除DataError
中定义的值之外的其他值。我通过处理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
来完成此操作:
DataError
这适用于除第一行之外的所有行。通过调试,我已经确认{{1}}事件确实没有针对第一行触发。但是,行标题中有一个红色感叹号,声称“条件表达式中的数据类型不匹配”。
为什么第一行不像其他行一样?还请提出解决此问题的更好方法。
答案 0 :(得分:0)
尝试引用DataGridViewComboBoxCell而不是DataGridViewComboBoxColumn。在我自己的情况下,使用绑定到数据表的组合框,只有在引用单元格后,我才能将第一行更新为适当的新值。您可能只需要像我在下面的最后一行代码中那样重新分配值。
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