数据网格中的vb.net combox框

时间:2011-09-12 14:18:12

标签: .net vb.net

我有一个带有数据网格的组合框,但我希望用户可以像往常一样输入组合框;在那一刻它是一个固定的下拉列表。这是我的代码:

  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

1 个答案:

答案 0 :(得分:3)

原则上你不需要处理两个事件

第一个允许用户输入新值

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

第二个实际插入新值

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