Question DataGridView ComboBox Column.

aeskan

Well-known member
Joined
Aug 10, 2011
Messages
63
Programming Experience
3-5
Hi everybody :cheerful:

In a DataGridView one of the columns' type is DataGridViewComboBoxColumn. The question is: Which one of the events (in VB .NET 2010) exactly occures when we do select an item of a ComboBox on the DataGridView? Since CellEnter, CellClick, CellContentClick, CellEndEdit, CellValueChanged and etc occure before of selecting ComboBox items or after completing of the editing process, so is there an event for that or should I write a special new event trapper code for it?

Best wishes.
 
Last edited:
The grid, the column and the cell have no event for that because they know nothing about it. The DataGridView generally contains no controls and simply renders its contents. When you start editing a cell, a control of the appropriate type is created, in this case a ComboBox, and embedded in the cell. Anything that that ComboBox does is known only to that ComboBox. When you finish editing the cell, which usually occurs when you navigate away from it, the control is removed and, in the case of a ComboBox, its SelectedValue is assigned to the Value of the cell.

Just like any regular ComboBox, this embedded ComboBox will raise SelectedIndexChanged and SelectionChangeCommitted events. You can handle those events if you need to react to those changes. Be very careful how you use them though. For instance, you should not make changes to other cells in the row based on those events because the actual cell Value has not changed at that point. The user could press Escape to cancel editing session without committing the change and your other modified cells would then be incorrect.

Here's one way to handle the SelectedIndexChanged event of a ComboBox in a DataGridView:
Private WithEvents column0ComboBox As ComboBox

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    'Check whether we are editing the first column.
    If DataGridView1.CurrentCellAddress.X = 0 Then
        'Handle the event(s) of the control while we are editing.
        Me.column0ComboBox = DirectCast(e.Control, ComboBox)
    End If
End Sub

Private Sub DataGridView1_CellEndEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    'We are no longer editing so we no longer need to handle the event(s).
    Me.column0ComboBox = Nothing
End Sub

Private Sub column0ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles column0ComboBox.SelectedIndexChanged
    '...
End Sub
 
Back
Top