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.Data
Imports System.Data.SqlClient
Imports System.Configuration
Module MainModule
Sub Main()
' declare a dataview and assign it the values from GetEmployeesUnsorted()
Dim dvUnsorted As DataView = GetEmployeesUnsorted()
Console.WriteLine("+++++ Sorted Dataview ++++++")
'call our print function
PrintToConsole(dvUnsorted, "LastName")
' declare a dataview and assign it the values from GetEmployeesSorted()
Dim dvSorted As DataView = GetEmployeesSorted()
Console.WriteLine("+++++ Sorted Dataview ++++++")
'call our print function
PrintToConsole(dvSorted, "LastName")
' declare a dataview and assign it the values from GetEmployeesWithFilter()
Dim dvFiltered As DataView = GetEmployeesWithFilter()
Console.WriteLine("+++++ Filtered Dataview ++++++")
'call our print function
PrintToConsole(dvFiltered, "LastName")
Console.ReadLine()
End Sub
Private Sub PrintToConsole(ByVal dv As DataView, ByVal columnName As String)
'loop thru the dataview
For i As Integer = 0 To dv.Count - 1
'print the value in index i from the specified column
Console.WriteLine(dv(i)(columnName).ToString())
Next
End Sub
Private Function GetEmployeesSorted() As DataView
'get the connection string from app.config
Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionString")
'create a new connection and assign our connection string
Dim sqlConnection As SqlConnection = New SqlConnection(connectionString)
'create a new command and pass our sql statement and our connection object
Dim sqlCommand As 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
Dim sqlAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)
'create a new dataset to hold our data
Dim ds As DataSet = 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
Dim dv As DataView = New DataView(ds.Tables(0))
'apply a sort
dv.Sort = "Lastname Desc"
'close our connection
sqlConnection.Close()
'return our dataview
Return dv
End Function
Private Function GetEmployeesUnsorted() As DataView
'get the connection string from app.config
Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionString")
'create a new connection and assign our connection string
Dim sqlConnection As SqlConnection = New SqlConnection(connectionString)
'create a new command and pass our sql statement and our connection object
Dim sqlCommand As 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
Dim sqlAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)
'create a new dataset to hold our data
Dim ds As DataSet = 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
Dim dv As DataView = New DataView(ds.Tables(0))
'close our connection
sqlConnection.Close()
'return our dataview
Return dv
End Function
Private Function GetEmployeesWithFilter() As DataView
'get the connection string from app.config
Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionString")
'create a new connection and assign our connection string
Dim sqlConnection As SqlConnection = New SqlConnection(connectionString)
'create a new command and pass our sql statement and our connection object
Dim sqlCommand As 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
Dim sqlAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)
'create a new dataset to hold our data
Dim ds As DataSet = 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
Dim 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 connection
sqlConnection.Close()
'return our dataview
Return dv
End Function
End 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:

Download the source code here: SortingDataTables.zip (35.56 KB)
Posted
03-16-2005 1:47 AM
by
keithrull