Learning innovation along the way

How to sort a DataTable

Feb 8

Written by:
2/8/2008 1:15 PM  RssIcon

While working on one of my modules I had a request to be able to sort the items in my DataList alphabetically. This seemed to be a trivial thing as far as I was concerned so off I went.  I was using a DataTable to bind to the DataList control for viewing the links I was building.  So with a quick search on Google I came up with some sample code to give me the basics of what I wanted to accomplish.  So in the following I will present both a C# and VB version of the code for anyone to use in their applications.

VB.NET Version

   1:  Private Function AlphabeticSort(ByVal dtTable As DataTable, _
ByVal sortOrder As Integer) As DataTable
   2:      Dim dsSorted As New DataSet
   3:      Dim columnKey As String = "TabName"
   4:      Dim sortDirection As String = ""
   5:      Dim sortFormat As String = "{0} {1}"
   6:      Select Case sortOrder
   7:          Case 0
   8:              sortDirection = "ASC"
   9:          Case 1
  10:              sortDirection = "DESC"
  11:          Case Else
  12:              sortDirection = "ASC"
  13:      End Select
  14:      dtTable.DefaultView.Sort = String.Format(sortFormat, columnKey, sortDirection)
  15:      Return dtTable.DefaultView.Table
  16:  End Function

C# Version

   1:  private DataTable AlphabeticSort(DataTable dtTable, int sortOrder)
   2:  {
   3:      DataSet dsSorted = new DataSet();
   4:      string columnKey = "TabName";
   5:      string sortDirection = "";
   6:      string sortFormat = "{0} {1}";
   7:      switch(sortOrder)
   8:      {
   9:          case 0:
  10:              sortDirection = "ASC";
  11:              break;
  12:          case 1:
  13:              sortDirection = "DESC";
  14:              break;
  15:          default:
  16:              sortDirection = "ASC";
  17:              break;
  18:      }
  19:      dtTable.DefaultView.Sort = string.Format(sortFormat, columnKey, sortDirection);
  20:      return dtTable.DefaultView.Table;
  21:      }

As you can see the code is very familiar between the two.  This works excellent for doing an alphabetic sort and very fast as well.


Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel