Message 1 of 3
Datagridview error when using Escape key to undo
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I've had a few difficulties with the datagridview. I have a project written in VB.Net, I want in Datagridview, when I change a certain cell will check for duplicates or not. If has, will not change it and return old data.
But I can't use the Esc key to cancel editing and return old data. If my code used for the Form is not in Inventor it will work. But the Form used in the inventor is not.
My code is as follows:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.Rows.Add("1", False, "11")
DataGridView1.Rows.Add("2", False, "12")
DataGridView1.Rows.Add("3", False, "13")
DataGridView1.Rows.Add("4", False, "14")
End Sub
Private Sub DataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End Sub
Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
Dim i As Integer = 0
Dim namecolumn As String = "Name1"
If DataGridView1.Rows(e.RowIndex).Cells(namecolumn).Value Is Nothing Then
e.Cancel = True
MsgBox("Please type name.")
Else
Do While (i < DataGridView1.Rows.Count)
If (Not (DataGridView1.Rows(i).Cells(namecolumn).Value) Is Nothing) Then
If (i <> e.RowIndex) AndAlso (DataGridView1.Rows(e.RowIndex).Cells(namecolumn).Value.ToString() = DataGridView1.Rows(i).Cells(namecolumn).Value.ToString()) Then
e.Cancel = True
MsgBox("This name exist already. please type another.")
'return;
End If
End If
i = (i + 1)
Loop
End If
End Sub
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
If keyData = Keys.Escape Then
Dim dgvEditingControl = TryCast(Control.FromHandle(msg.HWnd), DataGridViewTextBoxEditingControl)
If dgvEditingControl IsNot Nothing Then
Return True
End If
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
End Class