VB.Net DatagridviewComboBoxColumn CellClick 行为

VB.Net DatagridviewComboBoxColumn CellClick behavior

我有一个从 DataTable 填充的 DatagridviewComboBoxColumn,每当我单击 DataGridViewComboBoxCell 的任何部分时,列表的第一个值都会显示为已被单击。但是,当我将焦点移动到另一个单元格而不选择一个值时,它就会消失。

奇怪的是,如果我将 ComboBox 值与 .Items.Add(" ") 一起应用,则行为不一致。任何人都可以阐明这个问题。 这是示例代码和 gif 图片:

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DataGridView1.Rows.Add()
    DataGridView1.Rows.Add()

    ''DataGridViewComboBoxColumn1
    DataGridViewComboBoxColumn1.Items.Add("Name1")
    DataGridViewComboBoxColumn1.Items.Add("Name2")

    'DataGridViewComboBoxColumn2
    Dim dt As New DataTable
    dt.Columns.Add("id")
    dt.Columns.Add("name")
    dt.Rows.Add("1", "Name1")
    dt.Rows.Add("2", "Name2")
    With DataGridViewComboBoxColumn2
        .ValueMember = dt.Columns(0).ColumnName
        .DisplayMember = dt.Columns(1).ColumnName
        .DataSource = dt
    End With
End Sub

End Class

成功复制了该行为,但我还在同一表单中添加了 2 个 ComboBox,结果相同

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()

        ''DataGridViewComboBoxColumn1


        DataGridViewComboBoxColumn1.Items.Add("Name1")
        DataGridViewComboBoxColumn1.Items.Add("Name2")

        'DataGridViewComboBoxColumn2
        Dim dt As New DataTable
        dt.Columns.Add("id")
        dt.Columns.Add("name")
        dt.Rows.Add("1", "Name1")
        dt.Rows.Add("2", "Name2")
        With DataGridViewComboBoxColumn2
            .ValueMember = dt.Columns(0).ColumnName
            .DisplayMember = dt.Columns(1).ColumnName
            .DataSource = dt
        End With

        ComboBox1.Items.Add("Name1")
        ComboBox1.Items.Add("Name2")

        With ComboBox2
            .ValueMember = dt.Columns(0).ColumnName
            .DisplayMember = dt.Columns(1).ColumnName
            .DataSource = dt
        End With

    End Sub
End Class

Click to see gif of form in action

我参考这个 post 找到了纠正该行为的方法: DataGridComboBoxColumn shows first value on CellEnter

这是我使用的代码:

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
      If TypeOf e.Control Is ComboBox Then
          Dim comboBox As ComboBox = DirectCast(e.Control, ComboBox)
          If DataGridView1.CurrentCell.Value Is Nothing Then comboBox.SelectedIndex = -1
      End If
    End Sub