【发布时间】:2013-06-14 09:38:22
【问题描述】:
我有一个绑定到DataTable 的DataGridView,而DataTable 又是从数据库中填充的。在这个网格中,我有几个DataGridViewComboBoxColumns,数据绑定到ArrayLists,如下所示:
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 事件确实不会在第一行触发。但是,行标题中有一个红色感叹号,声称“标准表达式中的数据类型不匹配”。
为什么第一行的行为与其他行不同?还请提出更好的方法来解决这个问题。
【问题讨论】:
-
我不确定,但任何表格的第一行大多是标题行。这不会造成什么吗?
-
我查过了。第一行(索引 0)是包含数据的第一行,而不是标题。
标签: .net vb.net datagridviewcombobox