0

验证用户在单元格中的输入后,在 CellValidating 事件中,如果输入的值无效,那么我将在进入编辑模式之前将值设置回最初在单元格中的值。

我的问题是,对于我在 DGV 中的三个日期字段,除非在单元格中输入实际有效日期,否则我无法使单元格退出编辑模式。我需要在日期字段中允许空字符串值。

我尝试在各个地方强制 DataGridView.EndEdit() ,但是,正如我所说,只有在编辑控件中有某个有效日期时,日期字段才会退出编辑模式。

这是我与此过程相关的代码:

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
4

0 回答 0