GeorgeK
GeorgeK

Reputation: 647

How to fire an event when the tab key is pressed in a textbox?

For the current application I am working on I want to simulate a combo box using my own custom control as I want it to be multi column and have some additional functionality. I am using a text box and a datagridview to do this.

I want to replicate the suggest/append that can be used with a regular combo box. I've got this working great. The user can begin to type, gets a list of suggestions and can use the up and down keys to scroll through entries.

I have already trapped the enter key to take the selected row as the value. This works perfectly but I would also like to trap the tab key and do the same, much like the functionality already embedded in a combo box control.

The problem is that, obviously vb.net uses the tab key to change the selected control and this fires before I can call my subroutine to take the selected row from my datagridview. I want to be able to cancel tabbing out of the control, or at least find a way to fire my code before it does.

Thanks in advance.

Upvotes: 3

Views: 13622

Answers (2)

derki
derki

Reputation: 620

the problem is in this case that pressing TAB key will loose focus on that input element you need to bind on keydown event and with callback function like this

   var code = e.keyCode || e.which;
   if (code == '9') {
     alert('Tab');
     return false;
   }

Upvotes: -2

LarsTech
LarsTech

Reputation: 81610

The TextBox also has an AcceptsTab property that works when Multiline = True.

With those conditions, you can now see if the tab key was pressed:

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) _
                             Handles TextBox1.KeyDown
  If e.KeyCode = Keys.Tab Then
    e.SuppressKeyPress = True
    'do something
  End If
End Sub

Upvotes: 6

Related Questions