我一直在使用 VS2005 和 VB.NET 进行项目,在这个项目中,我有一个 DataGridView,里面有 3 个 DataGridViewComboboxCell。我一直在尝试做的是,当用户从第一个 DataGridViewComboboxCell 中选择一个值时,其他 2 个单元格的值会发生变化。这是该部分的代码:
Private Sub DataGridView1_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If (TypeOf e.Control Is DataGridViewComboBoxEditingControl) AndAlso _
DataGridView1.CurrentCell.ColumnIndex = 1 Then
Dim cbo As ComboBox = TryCast(e.Control, ComboBox)
If (cbo IsNot Nothing) Then
RemoveHandler cbo.SelectedIndexChanged, AddressOf comboBox_SelectedIndexChanged
AddHandler cbo.SelectedIndexChanged, AddressOf comboBox_SelectedIndexChanged
End If
End If
End Sub
Private Sub comboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim combo As ComboBox = TryCast(sender, ComboBox)
Dim rowIndex As Long = DataGridView1.CurrentRow.Index
Dim valueType As Type = GetType(Long)
If (combo.SelectedValue IsNot Nothing) Then
Dim comboValueType As Type = combo.SelectedValue.GetType()
Dim p As Boolean = valueType.Equals(comboValueType)
If Not valueType.Equals(comboValueType) Then
Exit Sub
End If
End If
DataGridView1.Rows(rowIndex).Cells(2).Value = 'Some DB query to retrieve the value
End Sub
我遇到的第一个问题是,当我打开组合框列表并键入I
以选择以I
. 组合框不会刷新以选择此项,并且总是返回到组合框中的第一项,所以我要做的是改变他自己的 SelectedIndexChange 组合框的值,如下所示:
Private Sub comboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim combo As ComboBox = TryCast(sender, ComboBox)
Dim rowIndex As Long = DataGridView1.CurrentRow.Index
Dim valueType As Type = GetType(Long)
If (combo.SelectedValue IsNot Nothing) Then
Dim comboValueType As Type = combo.SelectedValue.GetType()
Dim p As Boolean = valueType.Equals(comboValueType)
If Not valueType.Equals(comboValueType) Then
Exit Sub
End If
End If
DataGridView1.Rows(rowIndex).Cells(1).Value = combo.SelectedValue
DataGridView1.Rows(rowIndex).Cells(2).Value = 'Some DB query to retrieve the value
End Sub
第二个问题是,当我键入另一个字母来选择一个以该字母开头的项目并且没有按 Enter 或单击我更改为另一个 DatagridViewComboboxCell 的项目时,再次引发 SelectedIndexChanged 事件的组合框将其值更改为中的第一个项目组合框。
知道为什么会这样吗?