I have a DatagridviewComboBoxColumn populated from a DataTable and whenever I click on any part of the DataGridViewComboBoxCell the first value of the list shows up as it had been clicked. However, when I move the focus to another cell without selecting a value, it disappears.
Strangely, the behavior is not consistent if I apply the ComboBox values with .Items.Add(" "). Can anyone shed some light on this issue. Here is a sample code and a gif image:
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
I found a way to correct the behavior by referring to this post: DataGridComboBoxColumn shows first value on CellEnter
Here is the code I have used:
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