Issue detecting checkbox state in DataGridView

5.6k views Asked by At

I have a DataGridView control in a .Net application that contains a checkbox column. I would like for the user to be able to edit the checkboxes. The issue that I am running into is that I cannot detect the state of the checkbox after the user checks it.

If the checkbox was originally checked, then it will return checked as soon as the DataGridViewCheckBoxCell gets focus. But, if I click on the checkbox again and unchecks it, then it still returns checked. From that point on, it will always return checked regardless of the actual state of the checkbox until it looses focus and gains it again.

Likewise, if the checkbox was originally unchecked, then when it gets focus it will return unchecked in the click event regardless of what the state of the checkbox actually is.

Here is my code.

    Private Sub grdTemplates_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdTemplates.CellContentClick
    Dim strValue As String = ""
    Try
        If Me.grdTemplates.Columns(e.ColumnIndex).Name = "colCurrentTemplate" Then
            'The user clicked on the checkbox column
            strValue = Me.grdTemplates.Item(e.ColumnIndex, e.RowIndex).Value

            'THIS VALUE NEVER CHANGES WHILE THE DataGridViewCheckBoxCell HAS FOCUS
            Me.lblTemplates.Text = strValue
        End If

    Catch ex As Exception
        HandleError(ex.ToString)
    End Try

End Sub

Thanks in advance,

Mike

1

There are 1 answers

0
CrazyTim On

Include this in your code:

Sub dataGridView1_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs) Handles dataGridView1.CurrentCellDirtyStateChanged
    If dataGridView1.IsCurrentCellDirty Then
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
    End If
End Sub

Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcelldirtystatechanged.aspx