We help IT Professionals succeed at work.

DatagridviewCheckBoxColumn Cancelling the check/uncheck

oak29 asked
I have a DatagridviewCheckBoxColumn that needs validation.  Basically, when I go to Check/uncheck the checkbox I do a check from the database and if my boolean method returns true I want to stop the check/uncheck and leave the column alone(I'll implement a messagebox to notify the user why the action can't take place).  I'm not sure which datagridview event I need or the syntax. Thanks in advance.
Watch Question

Most Valuable Expert 2012
Top Expert 2014

You can use the CellContentClick event and then put a check to find out which column was clicked to make sure only checkbox column causes the code to execute.


I've done this and have checked the to see if the column should be checked/unchecked in this event but I can't figure out how to cancel the action.  Any ideas
Private Sub dgv_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles dgv.CellContentClick
            With Me.dgv.Rows(e.RowIndex)
                If .Cells(1).ColumnIndex = e.ColumnIndex Then
                    If SomeClass.CheckIfToAllowCHeckUncheck() = False Then

                        MessageBox.Show("You can't check/uncheck this column.", "")
                        'Now what? How do I cancel the action
                    End If
                End If
            End With

        Catch ex As Exception
        End Try
    End Sub

Open in new window

Most Valuable Expert 2012
Top Expert 2014
Let's try another approach. Handle the EditControlShowing event of the grid


and if the control is a checkbox(not sure of type. Do your research), then bind to its CheckedChanged event and you can directly set it to checked/unchecked as desired.