How to handle the TextChanged event only when the user stops typing?

一世执手 提交于 2019-12-05 03:51:26

Create a System.Windows.Forms.Timer and reset it (e.g. stop then start it) after every keypress. If the timer event is triggered, disable the timer.

Use the Reactive Framework to trigger on a sequence of events. I'm not sure exactly how this would work, but you can read up on it here (Reactive Extensions for .NET) and see if it will fulfill your needs. There are a bunch of examples here too: Examples. The "Throttling" example may be what you're looking for.

1) Create a timer.

2) Create a handler for the Tick event of your timer. On each tick, check to see if enough idle time has elapsed, and if it has, STOP the timer and execute the query.

3) Whenever a keypress occurs on that textbox, RESTART the timer.

Add a second actionlistener that gets called whenever the user presses any key and when it gets called save the current time to a global variable. Then whenver your TextChanged event gets called it checks to see the time difference between the global variable and the current time.

If the difference is less than 300 milliseconds then start a timer to execute the query after 300 milliseconds. Then if the user presses another key it resets the timer first.

Alex Jolig

Thanks to @Brian's idea and this answer , I came up with my own version of using a timer to handle this issue. This worked fine for me. I hope it helps the others as well:

private Timer _tmrDelaySearch;
private const int DelayedTextChangedTimeout = 500;
private void txtSearch_TextChanged(object sender, EventArgs e)
{
    if (_tmrDelaySearch != null)
    _tmrDelaySearch.Stop();

    if (_tmrDelaySearch == null)
    {
        _tmrDelaySearch = new Timer();
        _tmrDelaySearch.Tick += _tmrDelaySearch_Tick;
        _tmrDelaySearch.Interval = DelayedTextChangedTimeout;
    }

    _tmrDelaySearch.Start();
}

void _tmrDelaySearch_Tick(object sender, EventArgs e)
{
    if (stcList.SelectedTab == stiTabSearch) return;
    string word = string.IsNullOrEmpty(txtSearch.Text.Trim()) ? null : txtSearch.Text.Trim();

    if (stcList.SelectedTab == stiTabNote)
    FillDataGridNote(word);
    else
    {
        DataGridView dgvGridView = stcList.SelectedTab == stiTabWord ? dgvWord : dgvEvent;
        int idType = stcList.SelectedTab == stiTabWord ? 1 : 2;
        FillDataGrid(idType, word, dgvGridView);
    }

    if (_tmrDelaySearch != null)
    _tmrDelaySearch.Stop();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!