在某些情况下,无法从EditMode中获取DataGridView

时间:2014-12-08 16:50:43

标签: vb.net validation datagridview editmode

在单元格中验证用户的条目后,在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

0 个答案:

没有答案