Vb.net / DataGridView / ComboBox Column

datagridviewqcomboboxvb.net

I am using vb.net and winforms.

I have a Form with a Bound DataGridView. On the DGV I have 5 columns with ComboBox. I am using the EditingControlShowing Even to catch the ComboBox Selection. (see code bellow).
Here is the problem:

After I click on a Cell with a ComboBox and make a Selection and then update the underlying cell (cell = selected value) and then click on another Row of the DGV it goes haywire. If after I update the Cell I do and EndEdit on the corresponding row of the DataSource it seems to work find.

How can I determine whe corresponding Data Source row so that I can automate this?

Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) _
                Handles DataGridView1.EditingControlShowing
        Try
            Debug.Print("entered the EditingControlShowing")
            Dim ColName As String = Me.DataGridView1.Columns(Me.DataGridView1.CurrentCell.ColumnIndex).Name
            If ColName = "Col1" Then 'Or ColName = "Col2" Or ColName = "Col3" Or ColName = "Col4" Or ColName = "Col5" Then

'the column you want to cast
        Dim cmb As ComboBox = TryCast(e.Control, ComboBox)
            RemoveHandler cmb.SelectedIndexChanged, AddressOf cmb_SelectedIndexChanged
            AddHandler cmb.SelectedIndexChanged, AddressOf cmb_SelectedIndexChanged
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Sub cmb_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    Try
        Me.DataGridView1.Rows(Me.DataGridView1.CurrentRow.Index).Cells(Me.DataGridView1.CurrentCell.ColumnIndex).Value = CType(sender, ComboBox).SelectedItem
        '
        ' HERE IF I PUT MyDataSet.Tables(0).Rows(?).EndEding it works - but how to konw what row?
        '
        UpdateAvgColumn(Me.DataGridView1.CurrentRow.Index)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Best Answer

The events being fired are reentering. If you are currently processing an event, you have to be careful not to process other events. You have to put IF statements around the processing of the events to skip executing the code, if a different event is being processed.

sub dgv_selecteditemchanged()
  If not processing_event
    processing_event = true
    ...
    processing_event = false
  end if
end sub
Related Topic