I have just written my first program that queries a SQL database with the information a user writes into a textbox. This is C# using windows forms. My goal is to have this be similar to the search function in our ERP software where results are displayed as a user types (similar to Google's prediction search feature).
What I am struggling with is reducing the number of queries to the database. Right now I have it so that a query is not executed until the user has typed as least 3 characters otherwise too many results would be returned.
private void SearchField_TextChanged(object sender, EventArgs e)
{
string search = SearchField.Text;
if (search.Length >= 3)
{
dataGridView1.DataSource = sql.ExecuteQuery(Query(search));
}
}
What I want to add is a query delay until the user has stopped typing or rather not entered a character for so many milliseconds. I have been looking at the timer class but struggling with the examples I found to implement it properly. Basically I want to change my code to be something like the following:
private void SearchField_TextChanged(object sender, EventArgs e)
{
string search = SearchField.Text;
if (search.Length >= 3 && aTimer.Time > 500) //500 is milliseconds
{
dataGridView1.DataSource = sql.ExecuteQuery(Query(search));
}
aTimer.Reset();
}
If using the timer class I don't know how to implement it properly. If there is a better solution I would be open to that as well.