获取 `DataGridViewComboBox` 的选定索引

Get selected index of `DataGridViewComboBox`

当你在DataGridView中添加一个ComboBoxColumn时,我不知道如何处理ComboBox的变化事件。

'Adding To DGV data on form load
Dim cmbovoce As New DataGridViewComboBoxColumn()
cmbovoce.HeaderText = "Fruit"
cmbovoce.Name = "cmbovoce"
cmbovoce.MaxDropDownItems = 4
cmbovoce.Width = 100
cmbovoce.Items.Add("apple")
cmbovoce.Items.Add("pear")
cmbovoce.Items.Add("cherries")
cmbovoce.Items.Add("plums")
DataGridView1.Columns.Add(cmbovoce)

我强烈建议您使用 Cell 事件,例如 CellValidatingCellValueChanged、...来检测变化。您尝试处理其 SelectedIndexChange 事件的组合框是所有单元格的唯一实例。

无论如何,如果你想知道如何处理它的SelectedIndexChange事件,你可以这样做:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim c = New DataGridViewComboBoxColumn()
    c.HeaderText = "Fruit"
    c.Name = "c"
    c.MaxDropDownItems = 4
    c.Width = 100
    c.Items.Add("apple")
    c.Items.Add("pear")
    c.Items.Add("cherries")
    c.Items.Add("plums")
    Me.DataGridView1.Columns.Add(c)

    For index = 1 To 5
        Me.DataGridView1.Rows.Add()
    Next
End Sub

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    If (TypeOf (e.Control) Is ComboBox) Then
        Dim combo = CType(e.Control, ComboBox)
        RemoveHandler combo.SelectedIndexChanged, AddressOf c_SelectedIndexChanged
        AddHandler combo.SelectedIndexChanged, AddressOf c_SelectedIndexChanged
    End If
End Sub

Private Sub c_SelectedIndexChanged(sender As Object, e As EventArgs)
    If (Me.DataGridView1.Columns(Me.DataGridView1.CurrentCell.ColumnIndex).Name = "c") Then
        Dim combo = CType(sender, ComboBox)
        'Do something with combo
    End If
End Sub