.net ontextchanged,等到用户完成写入

时间:2012-05-08 12:58:34

标签: .net vb.net winforms

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

如何在用户完成写作时或每次用户稍作休息时才进行查询?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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

答案 3 :(得分: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
相关问题