Get selected index of `DataGridViewComboBox`

ⅰ亾dé卋堺 提交于 2019-12-02 06:33:25

I strongly recommend you to use Cell events, such as CellValidating, CellValueChanged, ... to detect changes. The combobox that you are trying to handle its SelectedIndexChange event, is a unique instance for all cells.

Anyway, if you want to know how to handle SelectedIndexChange event of it,you can do it this way:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!