After validating a user's entry in a cell, in the CellValidating event, if the entered value isn't valid, then I am setting the value back to what was in the cell initially, before entering Edit Mode.
My problem is, for the three Date fields I have in my DGV, I can't get the cell out of Edit Mode unless an actual valid date is entered in the cell. I need to allow empty string values in the date fields.
I tried forcing DataGridView.EndEdit() in various places, but, as I said, Date fields will only exit edit mode if some valid date is in the edit control.
Here's my relevant code for this process:
Private initailEditControlText As String = ""
Private passedValidation As Boolean = True
Private Sub dgvEmployees_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgvEmployees.EditingControlShowing
initailEditControlText = e.Control.Text
End Sub
Private Sub dgvEmployees_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvEmployees.CellValidating
Dim enteredValue As String = dgvEmployees.Rows(e.RowIndex).Cells(e.ColumnIndex).EditedFormattedValue.ToString()
If e.ColumnIndex > 0 AndAlso dgvEmployees.Rows(e.RowIndex).Cells(e.ColumnIndex).IsInEditMode Then
If enteredValue = "" Then
' Default/empty Goals cells value is 0
If e.ColumnIndex = 13 OrElse e.ColumnIndex = 14 Then
dgvEmployees.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "0"
End If
ElseIf e.ColumnIndex = 4 Then
' Validation for the various cells based on e.columnIndex
' If failed, passedValidation set to FALSE
End If
If Not passedValidation Then
' Set value back to original value
dgvEmployees.EditingControl.Text = initailEditControlText
e.Cancel = True
Else
If initailEditControlText <> enteredValue Then
dgvEmployees.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.BackColor = Color.LightPink
End If
End If
passedValidation = True
End If
End Sub
Private Sub dgvEmployees_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles dgvEmployees.DataError
If Not passedValidation Then
MessageBox.Show("Data error: " & vbCrLf & e.Exception.Message().ToString(), "An Error Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error)
' For Date fields, the error message is: "String was not recognized as a valid DateTime."
'Else
' This causes an infinite loop for some reason...
' dgvEmployees.EndEdit()
End If
End Sub