Finding, Filtering, and Sorting Rows in a DataTable
Each row in a DataTable is stored in a DataRow object, and in this section you'll learn
how to find, filter, and sort the DataRow objects in a DataTable.
Finding a DataRow in a DataTable
To find a DataRow in a DataTable, you follow these steps:
1. Retrieve the rows from the database into your DataTable.
2. Set the PrimaryKey property of your DataTable.
3. Call the Find() method of your DataTable, passing the primary key column value
of the DataRow you want.
For example, the following code performs steps 1 and 2 in this list, retrieving the top 10
rows from the Products table and setting the PrimaryKey property to the ProductID
DataColumn:
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT TOP 10 ProductID, ProductName " +
"FROM Products " +
"ORDER BY ProductID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet, "Products");
mySqlConnection.Close();
DataTable productsDataTable = myDataSet.Tables["Products"];
productsDataTable.PrimaryKey =
new DataColumn[]
{
productsDataTable.Columns["ProductID"]
};
Next, the following example performs step 3, calling the Find() method to retrieve the
DataRow from productsDataTable that has a ProductID of 3:
DataRow productDataRow = productsDataTable.Rows.Find("3");
Notice that the Find() method is called through the Rows property of productsDataTable.
The Rows property returns an object of the DataRowCollection class.
If the primary key for the database table consists of more than one column, then you can
pass an array of objects to the Find() method. For example, the Order Details table's
primary key is made up of the OrderID and ProductID columns. Assuming you've
already performed steps 1 and 2 and retrieved the rows from the Order Details table into a
DataTable object named orderDetailsDataTable, then the following example retrieves the
DataRow with an OrderID and ProductID of 10248 and 11, respectively:
object[] orderDetails =
new object[]
{
10248,
11
};
DataRow orderDetailDataRow = orderDetailsDataTable.Rows.Find(orderDetails);
Filtering and Sorting DataRow Objects in a DataTable
To filter and sort the DataRow objects in a DataTable, you use the Select() method of
your DataTable. The Select() method is overloaded as follows:
DataRow[] Select()
DataRow[] Select(string filterExpression)
DataRow[] Select(string filterExpression, string sortExpression)
DataRow[] Select(string filterExpression, string sortExpression,
DataViewRowState myDataViewRowState)
where
•
filterExpression specifies the rows to select.
•
sortExpression specifies how the selected rows are to be ordered.
•
myDataViewRowState specifies the state of the rows to select. You set
myDataViewRowState to one of the constants defined in the
System.Data.DataViewRowState enumeration. Table 11.8
shows these constants.
Table 11.8: DataViewRowState ENUMERATION MEMBERS
CONSTANT DESCRIPTION
Added A new row.
CurrentRows The current rows, which include Unchanged, Added, and
ModifiedCurrent rows.
Table 11.8: DataViewRowState ENUMERATION MEMBERS
CONSTANT DESCRIPTION
Deleted A deleted row.
ModifiedCurrent A current row that has been modified.
ModifiedOriginal The original row before it was modified.
None Doesn't match any of the rows in the DataTable.
OriginalRows The original rows, which include Unchanged and Deleted rows.
Unchanged A row that hasn't been changed.
Let's take a look at some examples that use the Select() method.
The following example calls the Select() method with no parameters, which returns all
rows in the DataTable without any filtering or sorting:
DataRow[] productDataRows = productsDataTable.Select();
The next example supplies a filter expression to Sort(), which returns only the DataRow
objects with ProductID DataColumn values that are less than or equal to 5:
DataRow[] productDataRows = productsDataTable.Select("ProductID <= 5");
The following example supplies both a filter expression and a sort expression that orders
the DataRow objects by descending ProductID values:
DataRow[] productDataRows = productsDataTable.Select("ProductID <= 5", "ProductID
DESC");
The next example supplies a DataViewRowState of OriginalRows to the previous
Select() call:
DataRow[] productDataRows =
productsDataTable.Select("ProductID <= 5", "ProductID DESC",
DataViewRowState.OriginalRows);
As you can see from the previous examples, the filter and sort expressions are similar to
WHERE and ORDER BY clauses in a SELECT statement. You can therefore use very
powerful expressions in your calls to the Sort() method. For example, you can use AND,
OR, NOT, IN, LIKE, comparison operators, arithmetic operators, wildcard characters,
and aggregate functions in your filter expressions.
Note For full details on how to use such filter expressions, refer to the
DataColumn.Expression property in the .NET online documentation.
The following example that uses the LIKE operator and the percent wildcard character
(%)-which matches any number of characters-to filter rows with a ProductName that start
with Cha. The example also sorts the rows by descending ProductID and ascending
ProductName values:
productDataRows =
productsDataTable.Select("ProductName LIKE 'Cha%'",
"ProductID DESC, ProductName ASC");
Notice that the string Cha% is placed in single quotes, which you must do for all string
literals.
Note You can also use a DataView object to filter and sort rows, and you'll learn how to
do that in Chapter 13
, "Using DataView Objects."
Listing 11.3
shows a program that finds, filters, and sorts DataRow objects.
Listing 11.3: FINDFILTERANDSORTDATAROWS.CS
/*
FindFilterAndSortDataRows.cs illustrates how to find, filter,
and sort DataRow objects
*/
using System;
using System.Data;
using System.Data.SqlClient;
class FindFilterAndSortDataRows
{
public static void Main()
{
SqlConnection mySqlConnection =
new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT TOP 10 ProductID, ProductName " +
"FROM Products " +
"ORDER BY ProductID;" +
"SELECT TOP 10 OrderID, ProductID, UnitPrice, Quantity " +
"FROM [Order Details] " +
"ORDER BY OrderID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
mySqlConnection.Open();
mySqlDataAdapter.Fill(myDataSet);
mySqlConnection.Close();
myDataSet.Tables["Table"].TableName = "Products";
myDataSet.Tables["Table1"].TableName = "Order Details";
// set the PrimaryKey property for the Products DataTable
// to the ProductID column
DataTable productsDataTable = myDataSet.Tables["Products"];
productsDataTable.PrimaryKey =
new DataColumn[]
{
productsDataTable.Columns["ProductID"]
};
// set the PrimaryKey property for the Order Details DataTable
// to the OrderID and ProductID columns
DataTable orderDetailsDataTable = myDataSet.Tables["Order Details"];
orderDetailsDataTable.Constraints.Add(
"Primary key constraint on the OrderID and ProductID columns",
new DataColumn[]
{
orderDetailsDataTable.Columns["OrderID"],
orderDetailsDataTable.Columns["ProductID"]
},
true
);
// find product with ProductID of 3 using the Find() method
// to locate the DataRow using its primary key value
Console.WriteLine("Using the Find() method to locate DataRow object " +
"with a ProductID of 3");
DataRow productDataRow = productsDataTable.Rows.Find("3");
foreach (DataColumn myDataColumn in productsDataTable.Columns)
{
Console.WriteLine(myDataColumn + "= " + productDataRow[myDataColumn]);
}