views:

1959

answers:

2

Is there an easy way to move around controls on a form exactly the same way as the tab key? This includes moving around cells on a datagridview etc.

+2  A: 

using winforms you should set the Form KeyPreview property to true

and in the keypress event for the form you should have

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
       GetNextControl(ActiveControl, true).Focus();
}
Marioh
+2  A: 

Because the datagridview handles is own tab events for moving between the cells, you will have to create a custom datagrid control and override the onKeyUp event like so:

Public Class MyCustomDataGrid
    Inherits DataGridView

    Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter Then
            e.Handled = True
            Me.ProcessTabKey(Keys.Tab)
        Else
            MyBase.OnKeyUp(e)
        End If
    End Sub
End Class

That will process the enter key as a tab key when trying to tab though the datagrid cells, if you need to handle tab also on the form you will have to do what Marioh said, but with a little change.

Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter AndAlso Not ActiveControl.GetType() Is GetType(Class1) Then
            e.Handled = True
            Me.ProcessTabKey(Not e.Shift)
        Else
            MyBase.OnKeyUp(e)
        End If
    End Sub

You will just have to add a check for type of the active control otherwise the form will stop your custom datagrid tab code from working.

Nathan W