开发者

vb.net combox box within a datagrid

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
        .DataPropertyNa开发者_如何学运维me = "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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜