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:

  1. Create a C# Windows Forms application named SearchWindowsFormsDataGridView.

  2. Add the following controls to the Form1 design surface:

    • DataGridView named contactDataGridView

    • TextBox named findTextBox

    • Button named findButton with Text property = Find

    The completed layout of the Windows Form named Form1 is 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.

Layout for Form1 in SearchWindowsFormsDataGridView solution

Figure 8-39. Layout for Form1 ...

Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.