8.20. Searching a Windows Forms DataGridView Control
Problem
You need to use a search criteria specified by a user to locate a record displayed in a DataGridView without executing a query against the database.
Solution
Use the Find() method of the DataView bound to the DataGridView to locate a record in the sorted column of the DataGrid and reposition to that row in the DataGridView.
Follow these steps:
Create a C# Windows Forms application named
SearchWindowsFormsDataGridView.Add the following controls to the
Form1design surface:DataGridViewnamedcontactDataGridViewTextBoxnamedfindTextBoxButton named
findButtonwithTextproperty =Find
The completed layout of the Windows Form named
Form1is shown in Figure 8-39.
The C# code in Form1.cs in the project SearchWindowsFormsDataGridView is shown in Example 8-32. The solution creates a DataTable and filled with the Person.Contact table from AdventureWorks. A DataView is created based on the default view of the DataTable, its sort key is set to the ContactID (first) column, and it is bound to the DataGridView. Finally, a CurrencyManager is created from the DataView.
The event handler for the Find button uses the Find() method of the DataView to locate a record with the user-specified value in the DataView sort column. If a match is found, the CurrencyManager is used to select the matching record in the DataGridView.

Figure 8-39. Layout for Form1 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access