Reputation: 1603
I have a combobox with a datagrid, but I'd like the user to be able to type into the combobox like usual; At the minute it's a fixed dropdown. Here is my code:
Dim NewColumn As New DataGridViewComboBoxColumn() 'Declare new DGV CC
With NewColumn 'Set Properties
.DataPropertyName = "NewColumn" 'Name
.HeaderText = "New Column" 'Heading
.DropDownWidth = 160 'Width Of DropDown Box
.Width = 90 'Display Width
'.MaxDropDownItems = 5 'How Many Items To Drop Down At A Time
.FlatStyle = FlatStyle.Flat 'Appearance
.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
.Items.Add("Screw Fix 1") 'Add Some Text Items
.Items.Add("Fix 1")
.Items.Add("3 Stone")
.Items.Add("34 Stone")
.Items.Add("5")
.Items.Add("6")
.Items.Add("7")
.Items.Add("8")
.Items.Add("9")
.Items.Add("10")
End With
dgDetails.Columns.Add(NewColumn) 'Add The Column
Upvotes: 1
Views: 652
Reputation: 15242
There isn't natively you need to handle two events
The first to allow the user to type in the new value
Private Sub dataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dataGridView1.EditingControlShowing
Dim c As ComboBox = TryCast(e.Control, ComboBox)
If c IsNot Nothing Then
c.DropDownStyle = ComboBoxStyle.DropDown
End If
End Sub
The second to actually insert the new value
Private Sub dataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handels dataGridView1.CellValidating
Dim comboBoxColumn As DataGridView.Column = dataGridView1.Columns("yourColumnName")
If e.ColumnIndex = comboBoxColumn.Index Then
Dim eFV As Object = e.FormattedValue
If Not comboBoxColumn.Items.Contains(eFV) Then
comboBoxColumn.Items.Add(eFV)
comboBoxColumn.SelectedIndex = ComboBox.Items.Count - 1
End If
End If
End Sub
Upvotes: 3