DataGridViewCheckBoxColumn CellContentClick事件问题

时间:2017-05-02 06:54:59

标签: vb.net datagridview

我有一个带复选框列的DGV,我想在用户点击复选框时触发一个事件,触发事件系统后会检查复选框是否已选中,然后再做其他事情。问题是当我点击复选框时,系统总是先改变复选框状态,然后只触发下面的事件,如何让它首先触发事件,然后才改变复选框状态?

为了简单起见,我希望当用户点击复选框然后点击消息框提示时,如果MsgBoxResult.Yes然后CheckBox.Checked = True并触发下面的事件,如果MsgBoxResult.No则什么都不做。

我已经尝试将select case messagebox添加到下面的代码中,但系统仍然首先更改复选框状态然后只提示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 个答案:

答案 0 :(得分:1)

使用DataGridView.CurrentCellDirtyStateChanged Event,它在更改单元格的实际值之前上升。

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