How to sort a DataTable

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.

Technorati Tags: , , ,

del.icio.us Tags: , , ,

kick it on DotNetKicks.com

Posted on 2/8/2008 11:50:12 PM by admin

Permalink | Comments (2) | Post RSSRSS comment feed |

Categories: ASP.NET | C# | Visual Studio | VB.NET

Tags: , , ,

Comments

February 24. 2008 11:36

Simon Philpk

Why not expand your function to make it more robust and except a string value that represents your table column name?

Simon Philpk United Kingdom

February 25. 2008 02:30

Sam MacDonald

Yes I agree it could easily be made more robust with a simple string added for the column you wanted to sort on.

Sam MacDonald Canada

Comments are closed