1
votes

I have a DataGridView with a DataGridViewCheckBoxColumn column. The cell size is larger than the checkbox so to make it user-friendly I want the CellClick event to act as if the checkbox itself was clicked.

At the moment I do this in my CellClick event:

If e.ColumnIndex = dgv.Columns("CONFIRM").Index Then
        If CBool(dgv.Item("CONFIRM", e.RowIndex).Value) = True Then
            dgv.Item("CONFIRM", e.RowIndex).Value = False
        Else
            dgv.Item("CONFIRM", e.RowIndex).Value = True
        End If
End If

However, the checkbox does not actually change state until after the cell loses focus. I've seen many suggestions about handling different events (CellValueChanged, CurrentCellDirtyStateChanged) (e.g. http://www.codingeverything.com/2013/01/firing-datagridview-cellvaluechanged.html) and committing changes with:

If dgvDownloads.IsCurrentCellDirty Then
        dgvDownloads.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If

However this doesn't work, the dgv flickers but the checkbox doesn't change checked state.

How can I force the checkbox in a DataGridViewCheckBoxColumn to update it's state when the containing cell is clicked?

1

1 Answers

2
votes

Try it more like this:

Public Class FormDGV

    Private Sub FormDGV_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With DataGridView1
            .Columns.Add(New DataGridViewCheckBoxColumn With {
                         .Name = "Confirm",
                         .HeaderText = "Confirm"})
        End With
    End Sub

    Private Sub DataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
        If DataGridView1.IsCurrentCellDirty Then
            DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If
    End Sub

    Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        If CType(DataGridView1.Rows(e.RowIndex).Cells("Confirm").Value, Boolean) Then
            DataGridView1.Rows(e.RowIndex).Cells("Confirm").Value = False
        Else
            DataGridView1.Rows(e.RowIndex).Cells("Confirm").Value = True
        End If
        Validate()
    End Sub
End Class