Combobox KeyDown event handler fires multiple times

In VB.NET, I have a Combobox in WinForm. The form allows the user to enter a search term. When the user presses the Enter key, the database query is executed and the results are returned as a DataTable. The DataTable is then bound to the Combobox and the user can select the option they are looking for.

For the most part, this works great. However, we found that the code was executed multiple times. If I write my query and press the Enter key, I can step through the code TWO or THREE times. I don't want to send the same query to the database multiple times unless I need to. Any ideas or suggestions why the code will be executed multiple times?

Here is the code in question. 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

      

0


source to share


1 answer


Oddly enough, adding cbx.Focus () after doing a search fixes the problem. Here is the solution.



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()
        cbx.Focus()
        Me.Cursor = Cursors.Default
    End If
    Me.Cursor = Cursors.Default

End Sub

      

+1


source







All Articles