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 techniquesthe DataTable.Select( ) method, the DataTable.Rows.Find( ) method, and the DataView.RowFilter propertyto 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 void findButton_Click(object sender, System.EventArgs e) { // Get the table bound to the grid. DataTable dt = ((DataView)dataGrid.DataSource).Table; // Build the filter using contents of the text box. String filter = SHIPCOUNTRY_FIELD + " = '" + shipCountryTextBox.Text + "'"; // Locate the records using the Select( ) method of the DataTable. DataRow[] drc = dt.Select(filter); resultTextBox.Text = "DataTable.Select returned " + drc.Length + " record(s)." + Environment.NewLine; // Iterate over the collection of rows filtered in the previous step // and find them in the table using the Find( ) method of the // DataRowCollection for the DataTable. int findCount = 0; foreach(DataRow row in drc) { DataRow foundRow = dt.Rows.Find(row[ORDERID_FIELD]); if (foundRow != null) findCount++; } resultTextBox.Text += "DataTable.Rows.Find returned " + findCount + " record(s)." + Environment.NewLine; // Locate records using the RowFilter property of the DataView. DataView dv = new DataView(dt); dv.RowFilter = filter; resultTextBox.Text += "DataView.RowFilter returned " + dv.Count + " record(s)."; }
Discussion
There are three ways to locate one or more rows in a table:
- Use the Select( ) method of the DataTable to return an array of DataRow objects matching the specified filter criteria. By default, the rows in the array are ordered by the primary key or, lacking a primary key, by the order in which the rows were added to the table. A sort order can be specified in an optional argument. The Select( ) method also takes an optional argument that can also be used to select records matching a specified row state from the DataViewRowState enumeration.
- Use the Find( ) method of the DataRowCollection of the table to return a row matching the primary key value or values passed as an object argument or an array of object arguments, respectively. To use the Find( ) method, the DataTable to which the DataRowCollection belongs must have a primary key defined, otherwise a MissingPrimaryKeyException is raised. If the primary key does not exist in the DataRowCollection , the method returns null .
- Use a DataView based on the DataTable to locate records in one of the following ways:
- Use the RowFilter property of the DataView . Create a DataView based on the DataTable and set the RowFilter property to a filter expression.
- Use the Find( ) method of the DataView to return the index of the row matching the sort key value or values passed as an object argument or an array of object arguments, respectively. If the sort key value does not exist in the DataView , null is returned.
- Use the FindRows( ) method of the DataView to return an array of DataRowView objects whose columns match the specified sort key value. If the sort key value does not exist, an empty DataRowView array is returned.
For more information about the Find( ) and FindRows( ) methods of the DataView , see Recipe 3.9.