With True DBGrid, you can easily perform search either on the whole grid or just a specific column. Incremental search for a column in the grid, positions a grid to that row if a match is found. The incremental searching feature specifically uses the grid's KeyPress event and the grid's indexer to retrieve and compare data for the particular column.
Let's say the user wants to search for entries in a column using incremental search, for this purpose, the user can add a Timer component to the form, and then set the KeyPress and Tick events.
Complete the following steps:
In the Designer
Locate the Interval property for Timer1 in the Properties window and set it to 1000.
In Code
Add the following code to the Form_Load event:
C# |
Copy Code
|
---|---|
this.timer1.Interval = 1000;
|
Add the KeyPress event:
C# |
Copy Code
|
---|---|
private void c1TrueDBGrid1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { // we're handling the keystroke e.Handled = true; this._searchString += e.KeyChar; int count = this.c1TrueDBGrid1.Splits[0].Rows.Count; int start = this.c1TrueDBGrid1.Row; int current = (start + 1) % count; // we'll stop if we get back to our starting position while( current != start ) { // get the value string s = this.c1TrueDBGrid1[current, this.c1TrueDBGrid1.Col].ToString(); // if we find a match, we're done if(!string.IsNullOrEmpty(s) && s.Length >= _searchString.Length && s.Substring(0, _searchString.Length).ToUpper() == _searchString.ToUpper() ) break; // search the next row, wrap if we need too current = (current + 1) % count; } // update the grid's current row this.c1TrueDBGrid1.Row = current; // clears the search string this.timer1.Enabled = true; } |
Add the Tick event for the timer:
C# |
Copy Code
|
---|---|
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this._searchString = string.Empty; this.timer1.Enabled = false; } |
As the user types, the search will highlight the cell containing that letter. If more than one entry begins with the same letter, typing the next letter will highlight the entry with those letters.