O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.8. Finding Rows in a DataTable

Problem

You need to find a row or group of rows in a DataTable meeting certain criteria.

Solution

Choose from the three techniques shown in the sample code to locate data in the table meeting user-specified criteria.

The sample code contains two event handlers:

Form.Load

Sets up the sample by creating a DataTable containing the Orders table from the Northwind sample database. The default view of the table is bound to the data grid on the form.

Find Button.Click

Uses three different techniques—the DataTable.Select( ) method, the DataTable.Rows.Find( ) method, and the DataView.RowFilter property—to find rows in the Orders table matching the user-specified Country.

The C# code is shown in Example 3-8.

Example 3-8. File: FindDataTableRowsForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; // Table name constants private const String ORDERS_TABLE = "Orders"; // Field name constants private const String ORDERID_FIELD = "OrderID"; private const String SHIPCOUNTRY_FIELD = "ShipCountry"; // . . . private void FindDataTableRowsForm_Load(object sender, System.EventArgs e) { // Fill the Orders table. SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable dt = new DataTable(ORDERS_TABLE); da.Fill(dt); da.FillSchema(dt, SchemaType.Source); // Bind the table to the grid. dataGrid.DataSource = dt.DefaultView; } private ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required