Tiny bit of VB help needed!

Soldato
Joined
5 Aug 2006
Posts
4,261
I am sure there is something I am missing. It really cannot be that difficult, however my VB knowledge is shocking.

I have a form with a textbox (eg tbInput) and an ok button (eg btnOk)

What I would like, is when there user (or barcode scanner) has finished populating the textbox, and presses enter/return that the sub btnOk_Click is run.

I'm sure its real easy. But I have no idea how to do it! Using VB Express 2010 if that makes any difference.

Someones help would be much appreciated. :o

Kind Regards

Alec
 
Set up an event handler for KeyDown or KeyPress (whichever works/is available, depending on whether you're using WinForms or WPF) and check the key code; if it's a return, then manually call the code for the OK button (you may have to refactor it into a separate method).
 
Right, I just about get the first bit. Thanks for getting back to me, but need it in real simple terms as I've literally been programming in VB for half a day.

So in tbInput_KeyPress I've got

If System.Windows.Forms.Keys.Return = 1 Then

End If

So what goes in the middle to call up the code for the ok button?
 
Try something like this:

Code:
    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click

        DoStuff()

    End Sub

    Private Sub tbInput_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbInput.KeyDown

        If e.KeyCode = System.Windows.Forms.Keys.Return Then
            DoStuff()
            e.SuppressKeyPress = True
        End If

    End Sub

    Private Sub DoStuff()

        ' Do whatever you want here.

    End Sub

Here you're checking the KeyEventArgs object passed into the event handler for the text box KeyDown event (the KeyPress event doesn't supply enough information), and if it's equal to the Return key, DoStuff is called. e.SuppressKeyPress is used to prevent the Return key from having any other effect (usually it'll make a noise as it's an invalid key, unless the text box is in multi-line mode).

Since the logic for the OK button is actually used in two situations, it make sense to encapsulate it into its own function/subroutine/method (i.e. DoStuff).
 
If you look at the form properties, there is a parameter called "AcceptButton". You can choose a button on the form that registers as "being clicked", when ENTER is pressed.
 
Back
Top Bottom