1

我有一个查询数据库并在下面的框中显示结果的搜索框。当我使用 ontextchanged 事件时,这有点慢,因为每次写入新字母时都会查询数据库。

我怎样才能让它只在用户写完之后才进行查询,或者每次用户休息一下?

4

4 回答 4

2

我对此的解决方案是在每次更改密钥时触发 Timer。我跟踪文本更改的次数,并将其与计时器过期的次数进行比较。如果两个数字相等,则调用该方法。注意:MySearchMethod() 是用户停止输入后触发的方法,而 txtQuickSearch 是用户正在输入的文本框的 ID。

Private mint_LastReceivedTimerID As Integer = 0
Private mint_LastInitializedTimerID As Integer = 0

Private Sub txtQuickSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles txtQuickSearch.TextChanged
    'Increment the counter for the number of times the textbox has been changed
    mint_LastInitializedTimerID = mint_LastInitializedTimerID + 1

    'Wait longer for shorter strings or strings without spaces
    Dim intMilliseconds As Integer = 500
    If txtQuickSearch.Text.Length >= 6 Then
        intMilliseconds = 250
    End If
    If txtQuickSearch.Text.Contains(" ") = True And txtQuickSearch.Text.EndsWith(" ") = False Then
        intMilliseconds = 175
    End If

    Dim objTimer As New System.Timers.Timer(intMilliseconds)
    AddHandler objTimer.Elapsed, AddressOf txtQuickSearch_TimerElapsed

    objTimer.AutoReset = False
    objTimer.Enabled = True
End Sub

Private Sub txtQuickSearch_TimerElapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
    'Increment the counter for the number of times timers have elapsed
    mint_LastReceivedTimerID = mint_LastReceivedTimerID + 1

    'If the total number of textbox changes equals the total number of times timers have elapsed (fire method for only the latest character change)
    If mint_LastReceivedTimerID = mint_LastInitializedTimerID Then
        'Fire method on the Main UI Thread
        Me.Dispatcher.Invoke(Sub() MySearchMethod(), System.Windows.Threading.DispatcherPriority.Normal)
    End If
End Sub
于 2014-03-14T17:08:08.660 回答
1

最简单的方法是记录最后一次 OnTextChanged 发生的时间。如果当前时间大于 N,则调用 web 服务。

另一种方法是每 N 毫秒开始一个重复时间,然后使用 lastText 检查文本,如果不相等则调用 Web 服务。如果您这样做,请使用 System.Windows.Form.Timer 以便在您从搜索框中获取当前文本时在 UI 上执行回调。

于 2012-05-08T13:07:44.180 回答
1

也许以 500 毫秒(半秒)的间隔连接一个 Timer 对象,并在 .onTextChanged 事件触发时启动它。然后当计时器“滴答”时,使用该事件将查询触发到数据库?

于 2012-05-08T13:03:18.507 回答
0

尝试这个:

Const WaitInterval As Integer = 5   '5 seconds <-- change this to control speed
Dim WithEvents MyTimer As New Timers.Timer

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    MyTimer.Interval = WaitInterval * 1000
    MyTimer.AutoReset = False
End Sub

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
    MyTimer.Stop()
    MyTimer.Start()
End Sub

Private Sub MyTimer_Elapsed(sender As Object, e As System.Timers.ElapsedEventArgs) Handles MyTimer.Elapsed

    '' -- call your method to query database here --

End Sub
于 2012-05-09T03:40:13.507 回答