I've got a method, that searches some data in DataGridView on KeyPress event and then focuses a row where input string was found (if is found).
private string input;
private void Find_Matches()
{
if (input.Length == 0) return;
for (int x = 0; x < dataGridViewCustomers.Rows.Count; x++)
for (int y = 0; y < dataGridViewCustomers.Columns.Count; y++)
if (dataGridViewCustomers.Rows[x].Cells[y].Value.ToString().Contains(input))
dataGridViewCustomers.Rows[x].Selected = true;
}
private void dataGridViewCustomers_KeyPress(object sender, KeyPressEventArgs e)
{
input += e.KeyChar.ToString();
Find_Matches();
}
How to count a delay between keys pressings and, if it is more than 1 second, clear the "input" string? It's necessary for uninterrupted searching.
Thanks.
leveraging System.Timers.Timer it's done like this:
private Timer myTimer = new Timer(1000); //using System.Timers, 1000 means 1000 msec = 1 sec interval
public YourClassConstructor()
{
myTimer.Elapsed += TimerElapsed;
}
private void TimerElapsed(object sender, EventArgs e)
{
input = string.Empty;
myTimer.Stop();
}
// this is your handler for KeyPress, which will be edited
private void dataGridViewCustomers_KeyPress(object sender, KeyPressEventArgs e)
{
if (myTimer.Enabled) myTimer.Stop(); // interval needs to be reset
input += e.KeyChar.ToString();
Find_Matches();
myTimer.Start(); //in 1 sec, "input" will be cleared
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With