组合框 KeyDown 事件处理程序多次触发

发布于 2024-07-09 19:02:17 字数 672 浏览 5 评论 0原文

在 VB.NET 中,我在 WinForm 窗体上有一个组合框。 该表单允许用户输入要搜索的查询。 当用户按下 Enter 键时,将对数据库执行查询,并将结果作为 DataTable 返回。 然后,数据表绑定到组合框,用户可以选择他们正在查找的选项。

在大多数情况下,这非常有效。 然而,我们发现该代码被执行了多次。 如果我写出查询并按一次 Enter 键,我可以单步执行代码两到三次。 如果不需要,我不想多次向数据库发送相同的查询。 为什么代码会执行多次有什么想法或建议吗?

这是有问题的代码。 组合框和函数名称已更改以保护无辜者。 :)

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

耶耶耶 2024-07-16 19:02:17

具有讽刺意味的是,在执行搜索后添加 cbx.Focus() 解决了问题。 这是解决方案。

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

Ironically, adding cbx.Focus() after the search has been performed fixed 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文