Reputation: 1598
I have a datagridview on my form currently. The idea that I'm trying to do is to catch a possible double entry issue when a user edits a cell in the datagridview. I'm supposed to check the field for a duplicate value (which CheckContestantList
already does by looping through each row and a possible match). On a match, the previous value is supposed to be restored and a messagebox should pop up and warn the user while resetting that field to edit mode.
However, when a user presses the Enter key... the current row indicator moves down by one... and throws everything off. I've already done a bit of reading on the matter but I can't seem to keep the current cell active even if someone presses Enter.
How do I allow for the Enter key to still confirm the enter press but not move down by one row?
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
Upvotes: 0
Views: 5267
Reputation: 1985
You are using the wrong datagridview
event, if you're gonna validate an input, you can use the _CellValidating
event.
Here's an example:
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
...
Now, for example the cell value is invalid, you can call the
e.Cancel = True
in the cell_validating
event so that the user cannot go to other cells unless the cell value is valid or press the ESC
key. This will exit the cell and return to its previous/original value.
Upvotes: 4