[ Team LiB ]Recipe 7.15 Adding Search Capabilities to Windows Forms
Problem
You need to use a search criteria specified by a user to locate a record displayed in a
DataGrid without executing a query against the database.
Solution
Use the Find( ) method of the DataView with a sort key value to locate a record displayed
in a DataGrid and reposition the row in the DataGrid.
The sample code contains two event handlers:
Form.Load
Sets up the sample by creating a DataTable and filling it with the Customers table
from the Northwind sample database. A DataView is created based on the default
view of the Customers DataTable, its sort key is set to the CustomerID column,
and it is bound to the data grid on the form. Finally, a CurrencyManager is created
from the DataView.
Go Button.Click
Uses the Find( ) method of the DataView to locate a record with the CustomerID
specified by the user. If the CustomerID is found, the CurrencyManager created in
the Form.Load event handler is used to select the matching record in the data grid.
The C# code is shown in Example 7-31
.
Example 7-31. File: SearchDataGridForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
int i = dv.Find(findTextBox.Text);
if(i < 0)
// A match was not found.
MessageBox.Show("No matching records found.", "Find",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
else
// Reposition the grid record using the CurrencyManager.
cm.Position = i;
}
else
{
MessageBox.Show("Enter find criteria.", "Find",
MessageBoxButtons.OK, MessageBoxIcon.Question);
findTextBox.Focus( );
}
}
Discussion
The Find( ) method of the DataView locates a row matching a specified sort key value.
The Sort property gets or sets the column or columns that the DataView is sorted on. The
Sort property is a string that contains the column name, or multiple column names
separated by commas, followed by an optional ASC or DESC clause specifying sort
direction.
There are two methods that you can use to locate records in a DataView:
Find( )
This method of the DataView returns the index of the first row matching the
specified sort key value or and array of sort key values, for sort keys based on
multiple columns. If no records match, it returns -1.
FindRows( )
This method of the DataView returns an array of rows matching the specified sort