DataGridView CheckBox Value

There are a few gotchas with checking the value of a CheckBox in a DataGridView. You can use the CellValueChanged event, the bound object will have been updated so its easy to check…

Private Sub PaymentsDataGridView_CellValueChanged(ByVal sender As System.Object, _
            ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
                Handles PaymentsDataGridView.CellValueChanged
    'This code will be called while loading the grid as well so I
    'just check for it by setting a flag
    If Not _Loading AndAlso e.ColumnIndex = 4 AndAlso e.RowIndex >= 0 Then
        Dim aSummary As RebatePatientSummary = _
                DirectCast(PaymentsDataGridView.Rows(e.RowIndex).DataBoundItem, _
                        RebatePatientSummary)
        If aSummary.PrintMe Then
            _PrintCount += 1
        Else
            _PrintCount -= 1
        End If
        AvailableToPrintLabel.Text = "Selected for printing : " & _PrintCount
     End If
End Sub

That gotcha here though is that the event is only fired once the cell has lost focus!

You can use the CurrentCellDirtyStateChanged but that only fires once so if the user clicks the checkbox multiple times you don’t actually know the final state


Leave a Reply