VB.Net DatagridviewComboBoxColumn CellClick行为

时间:2016-06-23 10:14:40

标签: vb.net datagridviewcombobox datagridviewcomboboxcell

我有一个从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

enter image description here

2 个答案:

答案 0 :(得分:0)

成功复制了该行为,但我还在同一表单中添加了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

答案 1 :(得分:0)

我找到了一种通过引用这篇文章来纠正行为的方法: 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