Public Class Form1 Private lastcol As Boolean = False Private Sub DGVCellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgv1.CellEnter If e.ColumnIndex = dgv1.Columns.Count - 1 Then lastcol = True Else lastcol = False End If End Sub Private Sub FormKeyDown(sender As Object, e As KeyEventArgs) Handles dgv1.KeyDown If lastcol = True Then e.Handled = True End If End Sub End Class
No, it won't, OP asked only to add this behaviour when last cell was in edit mode.This will do it for you
This will do it for you
Public Class Form1 Private lastcol As Boolean = False Private Sub DGVCellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgv1.CellEnter If e.ColumnIndex = dgv1.Columns.Count - 1 Then lastcol = True Else lastcol = False End If End Sub Private Sub FormKeyDown(sender As Object, e As KeyEventArgs) Handles dgv1.KeyDown If lastcol = True Then e.Handled = True End If End Sub End Class
Public Class Form1 Private Property ColNo() As Integer Private Sub dgv2_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgv2.CellEnter 'track column index ColNo = e.ColumnIndex End Sub Private Sub dgv2_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgv2.EditingControlShowing 'handle key event in edit mode Dim txtControl = DirectCast(e.Control, TextBox) AddHandler txtControl.PreviewKeyDown, AddressOf PreviewKeyDownMethod End Sub Private Sub PreviewKeyDownMethod(ByVal sender As Object, ByVal e As PreviewKeyDownEventArgs) 'check for tab key If e.KeyCode = Keys.Tab Then CancelKey() End If Dim txtControl = DirectCast(sender, TextBox) RemoveHandler txtControl.PreviewKeyDown, AddressOf PreviewKeyDownMethod End Sub Private Sub CancelKey() 'replace tab with escape if last column If ColNo = dgv2.Columns.Count - 1 Then Windows.Forms.SendKeys.SendWait("{ESC}") End If End Sub End Class
Well, I could grant you one more minuteI didn't see any event to overwrite for a quick fix, but if you have 10 mins would be great to see the inheritance method for learning sake.
Public Class DataGridViewEx Inherits DataGridView Protected Overrides Function ProcessDialogKey(keyData As System.Windows.Forms.Keys) As Boolean If Me.CurrentCellAddress.X = Me.ColumnCount - 1 AndAlso keyData = Keys.Tab Then Me.EndEdit() Return True End If Return MyBase.ProcessDialogKey(keyData) End Function End Class