Here's the simplest way to sort and filter data in a DataTable. Use DataView.
Note: This demo connects to an SQL Server and uses the Northwind database. You need to modify the App.config to make this demo work.
Here's the C# sample.
using System;using System.Data;using System.Data.SqlClient;using System.Configuration;namespace SortingDataTables{ /// <summary> /// Summary description for Class1. /// </summary> class MainClass { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // declare a dataview and assign it the values from GetEmployeesUnsorted() DataView dvUnsorted = GetEmployeesUnsorted();Console.WriteLine("+++++ Unsorted Dataview ++++++"); //call our print function PrintToConsole(dvUnsorted,"LastName"); // declare a dataview and assign it the values from GetEmployeesSorted() DataView dvSorted = GetEmployeesSorted(); Console.WriteLine("+++++ Sorted Dataview ++++++"); //call our print function PrintToConsole(dvSorted,"LastName"); // declare a dataview and assign it the values from GetEmployeesWithFilter() DataView dvFiltered = GetEmployeesWithFilter(); Console.WriteLine("+++++ Filtered Dataview ++++++"); //call our print function PrintToConsole(dvFiltered,"LastName"); //pause Console.ReadLine(); } private static void PrintToConsole(DataView dv, string columnName) { //loop thru the dataview for(int i =0; i < dv.Count; i++) { //print the value in index i from the specified column Console.WriteLine(dv[i][columnName].ToString()); } } private static DataView GetEmployeesSorted() { //get the connection string from app.config string connectionString = ConfigurationSettings.AppSettings["ConnectionString"]; //create a new connection and assign our connection string SqlConnection sqlConnection = new SqlConnection(connectionString); //create a new command and pass our sql statement and our connection object. SqlCommand sqlCommand = new SqlCommand("Select Lastname from Employees",sqlConnection); //open the connection sqlConnection.Open(); //create a new sqladapter and set its command object with our sqlcommand SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand); //create a new dataset to hold our data DataSet ds = new DataSet(); //fill the dataset with the result of our query from the specified command sqlAdapter.Fill(ds); //create a new dataview from our table in our dataset at index 0 DataView dv = new DataView(ds.Tables[0]); //apply a sort dv.Sort = "Lastname Desc"; //close our connection sqlConnection.Close(); //return our dataview return dv; } private static DataView GetEmployeesUnsorted() { //get the connection string from app.config string connectionString = ConfigurationSettings.AppSettings["ConnectionString"]; //create a new connection and assign our connection string SqlConnection sqlConnection = new SqlConnection(connectionString); //create a new command and pass our sql statement and our connection object. SqlCommand sqlCommand = new SqlCommand("Select Lastname from Employees",sqlConnection); //open the connection sqlConnection.Open(); //create a new sqladapter and set its command object with our sqlcommand SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand); //create a new dataset to hold our data DataSet ds = new DataSet(); //fill the dataset with the result of our query from the specified command sqlAdapter.Fill(ds); //create a new dataview from our table in our dataset at index 0 DataView dv = new DataView(ds.Tables[0]); //close our connection sqlConnection.Close(); //return our dataview return dv; } private static DataView GetEmployeesWithFilter() { //get the connection string from app.config string connectionString = ConfigurationSettings.AppSettings["ConnectionString"]; //create a new connection and assign our connection string SqlConnection sqlConnection = new SqlConnection(connectionString); //create a new command and pass our sql statement and our connection object. SqlCommand sqlCommand = new SqlCommand("Select Lastname from Employees",sqlConnection); //open the connection sqlConnection.Open(); //create a new sqladapter and set its command object with our sqlcommand SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand); //create a new dataset to hold our data DataSet ds = new DataSet(); //fill the dataset with the result of our query from the specified command sqlAdapter.Fill(ds); //create a new dataview from our table in our dataset at index 0 DataView dv = new DataView(ds.Tables[0]); //apply our row filter. get only records with a lastname of 'Callahan' dv.RowFilter = "LastName = 'Callahan'"; //close our connection sqlConnection.Close(); //return our dataview return dv; } }}
Here's the VB.NET sample.
Imports System.DataImports System.Data.SqlClientImports System.ConfigurationModule MainModuleSub Main()' declare a dataview and assign it the values from GetEmployeesUnsorted()Dim dvUnsorted As DataView = GetEmployeesUnsorted()Console.WriteLine("+++++ Sorted Dataview ++++++")'call our print functionPrintToConsole(dvUnsorted, "LastName")' declare a dataview and assign it the values from GetEmployeesSorted()Dim dvSorted As DataView = GetEmployeesSorted()Console.WriteLine("+++++ Sorted Dataview ++++++")'call our print functionPrintToConsole(dvSorted, "LastName")' declare a dataview and assign it the values from GetEmployeesWithFilter()Dim dvFiltered As DataView = GetEmployeesWithFilter()Console.WriteLine("+++++ Filtered Dataview ++++++")'call our print functionPrintToConsole(dvFiltered, "LastName")Console.ReadLine()End SubPrivate Sub PrintToConsole(ByVal dv As DataView, ByVal columnName As String)'loop thru the dataviewFor i As Integer = 0 To dv.Count - 1'print the value in index i from the specified columnConsole.WriteLine(dv(i)(columnName).ToString())NextEnd SubPrivate Function GetEmployeesSorted() As DataView'get the connection string from app.configDim connectionString As String = ConfigurationSettings.AppSettings("ConnectionString")'create a new connection and assign our connection stringDim sqlConnection As SqlConnection = New SqlConnection(connectionString)'create a new command and pass our sql statement and our connection objectDim sqlCommand As SqlCommand = New SqlCommand("Select Lastname from Employees", sqlConnection)'open the connectionsqlConnection.Open()'create a new sqladapter and set its command object with our sqlcommandDim sqlAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)'create a new dataset to hold our dataDim ds As DataSet = New DataSet'fill the dataset with the result of our query from the specified commandsqlAdapter.Fill(ds)'create a new dataview from our table in our dataset at index 0Dim dv As DataView = New DataView(ds.Tables(0))'apply a sortdv.Sort = "Lastname Desc"'close our connectionsqlConnection.Close()'return our dataviewReturn dvEnd FunctionPrivate Function GetEmployeesUnsorted() As DataView'get the connection string from app.configDim connectionString As String = ConfigurationSettings.AppSettings("ConnectionString")'create a new connection and assign our connection stringDim sqlConnection As SqlConnection = New SqlConnection(connectionString)'create a new command and pass our sql statement and our connection objectDim sqlCommand As SqlCommand = New SqlCommand("Select Lastname from Employees", sqlConnection)'open the connectionsqlConnection.Open()'create a new sqladapter and set its command object with our sqlcommandDim sqlAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)'create a new dataset to hold our dataDim ds As DataSet = New DataSet'fill the dataset with the result of our query from the specified commandsqlAdapter.Fill(ds)'create a new dataview from our table in our dataset at index 0Dim dv As DataView = New DataView(ds.Tables(0))'close our connectionsqlConnection.Close()'return our dataviewReturn dvEnd FunctionPrivate Function GetEmployeesWithFilter() As DataView'get the connection string from app.configDim connectionString As String = ConfigurationSettings.AppSettings("ConnectionString")'create a new connection and assign our connection stringDim sqlConnection As SqlConnection = New SqlConnection(connectionString)'create a new command and pass our sql statement and our connection objectDim sqlCommand As SqlCommand = New SqlCommand("Select Lastname from Employees", sqlConnection)'open the connectionsqlConnection.Open()'create a new sqladapter and set its command object with our sqlcommandDim sqlAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)'create a new dataset to hold our dataDim ds As DataSet = New DataSet'fill the dataset with the result of our query from the specified commandsqlAdapter.Fill(ds)'create a new dataview from our table in our dataset at index 0Dim dv As DataView = New DataView(ds.Tables(0))'apply our row filter. get only records with a lastname of 'Callahan'dv.RowFilter = "LastName = 'Callahan'"'close our connectionsqlConnection.Close()'return our dataviewReturn dvEnd FunctionEnd Module
Here is the App.Config for both project
<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="ConnectionString" value="server=[yourserver];database=Northwind;uid=[username];pwd=[password];" /> </appSettings></configuration>
The sample output of the demo:
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.