4.5. Filtering and Sorting Data in a DataTable
Problem
You have a DataTable filled with data, but you need to work with only a subset of the records and also to sort them. You need a way to both filter and sort the records in your DataTable without requerying the data source.
Solution
Use either the Sort and RowFilter properties of the DataView or the Select() method of the DataTable.
Choose from the two techniques shown in the solution to filter and sort records from table according to user-specified criteria.
The solution creates a DataSet containing data from the Production.Product table in AdventureWorks. Solutions are presented to illustrate how to use two different techniques—the RowFilter property of the DataView and the DataTable.Select() method—to filter and sort records.
The C# code in Program.cs in the project FillSortData that uses the Sort and RowFilter properties of the DataView is shown in Example 4-5.
Example 4-5. File: Program.cs for FillSortData solution
using System; using System.Data; using System.Data.SqlClient; namespace FilterSortData { class Program { static void Main(string[] args) { string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; string sqlSelect = "SELECT * FROM Production.Product"; // Fill the DataSet, mapping the default table name SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString); da.TableMappings.Add("Table", "Product"); DataSet ds = new DataSet(); da.Fill(ds); DataView dv = ds.Tables["Product"].DefaultView; ...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