Reputation: 27
So what my exact problem is, is that I want the program to wait 3 seconds and if nothing happens id should execute whatever method I called. But if someone enteres something in these 3 seconds the timer should start again.
Threadsleep doesnt work because it blocks everything and you cant give any inputs.
For example, I have a Filter function and now I dont want to filter right after he entered a letter, I wait 3 seconds and if nothing happend I start filtering. I need this so my Program wont take to long for filtering every single letter.
Here is my current code from the Filtermethod:
private void ContainsFilter(object sender, EventArgs e, TextBox textBox, DataGridView dataGridView, int columnIndex)
{
if (textBox.Text != "")
{
var value = "";
var filterText = "";
for (int i = 0; i < dataGridView.RowCount; i++)
{
value = Convert.ToString(dataGridView.Rows[i].Cells[columnIndex].Value);
value = value.ToLower();
filterText = textBox.Text;
filterText = filterText.ToLower();
if (value.Contains(filterText) == false)
{
dataGridView.Rows[i].Visible = false;
}
else
{
dataGridView.Rows[i].Visible = true;
}
}
return;
}
for (int i = 0; i < dataGridView.RowCount; i++)
{
dataGridView.Rows[i].Visible = true;
}
return;
}
Upvotes: 0
Views: 1158
Reputation: 87
I had the same request a while ago, the approach I used was to start searching when the user enters at least three letters
Upvotes: -1
Reputation: 473
It's pretty easy with System.Timers.Timer.
I try to give you a generic answer.
System.Timers.Timer timer = new System.Timers.Timer(3000);
timer.Elapsed += (sender, e) =>
{
// Filter
};
timer.AutoReset = false; // To execute and filter once, not repeatedly every 3 seconds.
Basically when the text changed. Do this:
timer.Stop(); // Stop the previous timer (in case it is not elapsed yet.)
timer.Start(); // and start it again. To run after 3 seconds.
When you fill you don't need it anymore. The program stopped, form closed, etc. Do this:
timer.Dispose();
Upvotes: 3