Enter Key and a Listbox

I read all of the post about the enter key. How do you get it to work on a listbox

I tried this in the listbox's keyup event with out any luck.

If e.KeyCode = Keys.Enter Then

Button2.PerformClick()

End If

Davids Learning



Answer this question

Enter Key and a Listbox

  • MarkBosley

    You may want to trap for the return key also ...they have two different key codes...so this should work no matter if you press enter or return:

    Private Sub ListBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ListBox1.KeyUp

    If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Return Then

    Button1.PerformClick()

    End If

    End Sub



  • JeroGrav

    have you implemented the listboxs' keydown event, and used the code you supplied there

    What happens when "it doesnt work"



  • cobain81

    the problem seems to be the "Handles" part of the code.

    it should not be "Me.KeyDown" but "EmployeeList.KeyDown", without the quotes.



  • borice

    Yes I have put it in both ,key up and key down,both are present

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

    If e.KeyCode = Keys.Enter Then

    MsgBox("HA")

    Button2.PerformClick()

    End If

    End Sub

    Private Sub EmployeeList_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp

    If e.KeyCode = Keys.Enter Then

    MsgBox("HA HA")

    Button2.PerformClick()

    End If

    End Sub

    Nothing happens - I put a msgbox in both of them and no msgbox

    Davids Learning


  • WoFe

    When I changed it to

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

    If e.KeyCode = Keys.Enter Then

    MsgBox("HA")

    Button2.PerformClick()

    End If

    End Sub

    I got an error with the Key.Down at the end of the statement being

    Handles clause requires a WithEvent variable defined in the containing type or one of its base types

    How do I correct this

    Davids Learning


  • hrubesh

    the best thing to do David, is to go into the form designer, click on the control and in the properties window, select the events icon (lightning symbol) and double click the KeyDown event to create the proper event handler, if you have not done so already.



  • qrli

    thats what I did the first time when it gave the Me.KeyDown.

    Davids Learning


  • Enter Key and a Listbox