验证DataGridView单元格

时间:2016-10-10 07:13:11

标签: vb.net datagridview

我目前在我的表单上有一个datagridview。我尝试做的想法是在用户编辑datagridview中的单元格时捕获可能的双重输入问题。我应该检查字段是否有重复值(CheckContestantList已经通过遍历每一行和可能的匹配来完成)。在匹配时,应该恢复之前的值并且弹出消息框并在将该字段重置为编辑模式时警告用户。

但是,当用户按下Enter键时...当前行指示器向下移动一个...并抛弃所有内容。我已经对此事做了一些阅读,但即使有人按下Enter键,我也似乎无法保持当前的单元格。

如何允许Enter键仍然确认输入按下但不能向下移动一行?

Private Sub dgvContestantPool_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvContestantPool.CellEndEdit
    ' On the editing of the field, check to see if the value already exists.

    If CheckContestantList(dgvContestantPool.CurrentCell.Value) = True Then

        ' Reset the value to the original value...
        dgvContestantPool.ClearSelection()
        dgvContestantPool.CurrentCell = dgvContestantPool.Rows(intCurrentRow).Cells("ContestantName")
        dgvContestantPool.Rows(intCurrentRow).Selected = True

        dgvContestantPool.CurrentCell.Value = strOldValue
        dgvContestantPool.BeginEdit(True)

        ' Alert the user to try again...
        MessageBox.Show("Entered value already exists in the list, try again or delete the entry.", "INVALID DATA - Already Exists", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        ' Go ahead and let the edit persists.
    End If

End Sub

Private Sub dgvContestantPool_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles dgvContestantPool.CellBeginEdit
    strOldValue = dgvContestantPool.CurrentCell.Value
    intCurrentRow = dgvContestantPool.CurrentRow.Index

End Sub

1 个答案:

答案 0 :(得分:3)

您使用了错误的datagridview事件,如果您要验证输入,则可以使用_CellValidating事件。

以下是一个例子:

 Private Sub dgvContestantPool_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvContestantPool.CellValidating
    If CheckContestantList(dgvContestantPool.Rows(e.RowIndex).Cells(e.ColumnIndex).EditedFormattedValue) = True Then
        'Your code goes here
    End If
 ...

现在,例如单元格值无效,您可以调用 e.Cancel = True事件中的cell_validating,除非单元格值有效或按ESC键,否则用户无法转到其他单元格。这将退出单元格并返回其先前/原始值。