In VB.NET, I have a Combobox on a WinForm form. The form allows the user to type in a query to be searched. When the user hits the Enter key, a query is performed against the database and the results are returned as a DataTable. The DataTable is then bound to the Combobox and the user can select the option that they are looking for.
For the most part, this is working great. However, we’ve discovered that the code is executing multiple times. If I write my query out and hit the Enter key ONCE, I can step through the code TWO or THREE times. I don’t want to send the same query to the database multiple times if I do not have to. Any ideas or suggestions why the code would be executing multiple times?
Here is the code in question. The Combobox and Function names have been changed to protect the innocent. 🙂
Private Sub cbx_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cbx.KeyDown Me.Cursor = Cursors.IBeam If e.KeyData = Keys.Enter Then Me.Cursor = Cursors.WaitCursor PerformSearch() Me.Cursor = Cursors.Default End If Me.Cursor = Cursors.Default End Sub
Ironically, adding cbx.Focus() after the search has been performed fixed the problem. Here is the solution.