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.LoadSets up the sample by creating a
DataTableand filling it with the Customers table from the Northwind sample database. ADataViewis created based on the default view of the CustomersDataTable, its sort key is set to the CustomerID column, and it is bound to the data grid on the form. Finally, aCurrencyManageris created from theDataView.- Go
Button.Click Uses the
Find( )method of theDataViewto locate a record with the CustomerID specified by the user. If the CustomerID is found, theCurrencyManagercreated in theForm.Loadevent 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; private DataView dv; private CurrencyManager cm; // . . . private void SearchDataGridForm_Load(object sender, System.EventArgs e) { // Create the DataAdapter and load the Customers data in a table. String sqlText = "SELECT * FROM Customers"; SqlDataAdapter da ...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