Start New Discussion within our Software Development Community

hello !
look , for example i have 2 textboxes in my vb form, i want that when i press enter key the focus move from 1st textbox to 2nd textbox , i use this code on my every control to move focus

if e.keychar = chr(keys.enter) then 
textbox2.focus ()

can any one help me to make a function to do same action when i press enter the focus move on next control , this sort of coding take so much time , :( please help me

Best Regards

M.Waqas Aslam

Hello waqasaslammmeo,

I use the following function to move to the control I want on the Enter Press. You must set the KeyPreview Property of the form to True. You can set up a Select Case if you have more than one you want to test for and move to. txtFuelCharge is a textbox as is txtTotal

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, _
                                             ByVal keyData As System.Windows.Forms.Keys) _
                                             As Boolean

    Dim cntrlName As String = ActiveControl.Name

    If keyData = Keys.Enter And cntrlName = txtFuelCharge.Name Then
      Return True
    End If

    'Close Connection to Access
    If keyData = Keys.F1 Then
      Friends.closeAccess = True
    End If

    Return False

  End Function

Not a Function, though it gets the job done.

Public Class Form1
    Private iT As Integer = Nothing '// TEMP.Integer to get # at end of TextBoxes.

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    End Sub

    Private Sub setHandlersForCoolTextBoxes()
        For Each txt As TextBox In New TextBox() {TextBox1, TextBox2, TextBox3, TextBox4} '// add your TextBoxes here.
            AddHandler txt.KeyDown, AddressOf _myCoolTextBoxes_KeyDown
    End Sub

    Private Sub _myCoolTextBoxes_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter Then setFocusToNextCoolTextBox(CType(sender, TextBox)) '// send current TextBox to Sub.
    End Sub

    Private Sub setFocusToNextCoolTextBox(ByVal selCurrentCoolTextBox As TextBox)
        With selCurrentCoolTextBox.Name
            iT = CInt(.Substring(.LastIndexOf("x") + 1)) + 1 '// get # at end of TextBo"x"# and add+1 for next TextBox, if Available.
        End With
        If Not CType(Me.Controls("TextBox" & iT.ToString), TextBox) Is Nothing Then '// if Available.
            With CType(Me.Controls("TextBox" & iT.ToString), TextBox)
                .BackColor = Color.LightSkyBlue  '// FOR.TESTING.
            End With
            MsgBox(".you need more TextBoxes you s.o.b.! xD", MsgBoxStyle.Information, ".just because.")
        End If
    End Sub
End Class
exactly what i needed :) cheers
This question has already been answered. Start a new discussion instead.