0
votes

I have a DGV with checkbox column, I want to trigger an event when user click on the checkbox, after trigger the event system will check if the checkbox checked then do nothing else do something. The problem is when I clicked the checkbox, system always change the checkbox state first then only trigger event below, how to make it trigger event below first then only change the checkbox state?

To make it simple, I want when user clicked on checkbox then messagebox prompt, if MsgBoxResult.Yes then CheckBox.Checked = True and trigger event below, if MsgBoxResult.No then do nothing.

I have try add select case messagebox to code below but system still change the checkbox state first then only prompt MessageBoxDialog

Private Sub dgv_supplier_CellContentClick(sender As System.Object, e As DataGridViewCellEventArgs) Handles dgv_supplier.CellContentClick
        Dim senderGrid = DirectCast(sender, DataGridView)

        If (e.ColumnIndex >= 0 And e.RowIndex >= 0) Then
            If TypeOf senderGrid.Columns(e.ColumnIndex) Is DataGridViewCheckBoxColumn AndAlso e.RowIndex >= 0 Then
                Dim index = e.RowIndex
                Dim currRow = dgv_supplier.Rows(index)
                Dim str_supName = currRow.Cells("sup_name").Value

                If currRow.Cells("checkbox").Value = True Then
                    Exit Sub
                Else
                    'Do something
                End If
            End If
        End If
    End Sub
1

1 Answers

1
votes

Use DataGridView.CurrentCellDirtyStateChanged Event, which raises before actual value of the cell is changed.

Private Sub dgv_supplier_CurrentCellDirtyStateChanged(
    sender As Object, 
    e As EventArgs) Handles dgv_supplier.CurrentCellDirtyStateChanged

    Dim senderGrid = DirectCast(sender, DataGridView)
    Dim cell = senderGrid.CurrentCell

    If cell.ColumnIndex < 0 Then Exit Sub
    If cell.RowIndex < 0 Then Exit Sub

    Dim checkBoxCell = TryCast(senderGrid.CurrentCell, DataGridViewCheckBoxColum)
    If checkBoxCell Is Nothing Then Exit Sub

    Dim currentRow = cell.OwningRow
    Dim str_supName = currentRow.Cells("sup_name").Value

    ' currentCell.Value is previous value before click
    If currentCell.Value = True Then 
        ' commit changes
        senderGrid.CommitEdit(DataGridViewDataErrorContexts.Commit)
    Else
        ' Do something
    End If
End Sub