Saturday, December 17, 2005

How to stay in a combo box after pressing the Enter key



I have a combo box called cmbrefnumber. The user will type a refnumber, or part of it, press Enter, and data for that refnumber will be displayed. Since the user most probably would like to enter another refnumber I would like the combo box to have focus after Enter is pressed.

This is how I achieved it:

Private Sub cmbrefnumber_AfterUpdate()
...
gbcmbrefnumberafterupdate = True
End Sub

Private Sub cmbrefnumber_Exit(Cancel As Integer)
If gbcmbrefnumberafterupdate Then
gbcmbrefnumberafterupdate = False
Cancel = True
cmbrefnumber.SelStart = 0 ' selects the refnumber
cmbrefnumber.SelLength = Len(cmbrefnumber.Text)
End If
End Sub

gbcmbrefnumberafterupdate is a global variable that remembers if the user has typed a new refnumber. If he has, the exit will be cancelled and gbcmbrefnumberafterupdate is set to false such that if no changes are made exit is permitted and the next control in the tab order gets the focus.

I found the answer here.

No comments: