Sorting a datatable for REALS! Just like they said in the South Park show where Kenny goes to heaven with his playstation system. "This is for reals."


Okay, folks here it is...

I'm a fan of Response.Write, and the other day, I needed to response.write the contents of a datatable. Don't ask me why. Just know that I had alot of neat javascript and ajax goodies going on. So, it was easier for me to just response.write the whole thing. Then I found out that...

misleading... :-( Code:
  1. mytable.DefaultView.Sort = "column asc"

Only works when you bind it, example a datagrid. This is a terrible thing. I can't believe, I was mislead to believe that DefaultView.Sort would do the trick. Shame on you world. lol. :-)

Here is a function I created that does real sorting on a datatable....



good stuff man... Code:
  1. Public Function SortTable(ByRef mytable As DataTable, ByVal column As String)
  2.         'Sorting a table for reals! By SiLentThReaD, AKA Numbchucks.
  3.  
  4.         'create a blank table. tablecopy is the name
  5.         Dim tablecopy As New DataTable
  6.         'make an exact copy of the table you passed in by reference, and
  7.         'store it in your tablecopy table
  8.         tablecopy = mytable.Copy()
  9.         'clear the contents of the table you just passed in, because
  10.         'you will soon fill it with newly sorted rows
  11.         mytable.Clear()
  12.         'create a rows array
  13.         Dim foundRows() As DataRow
  14.         'assign the foundrows array the values returned
  15.         'from the select. In this case, I left the
  16.         'filterexpression blank, because I want to get
  17.         'everything. I all I need to change is the sort
  18.         'order.
  19.         foundRows = tablecopy.Select("", column + " asc")
  20.  
  21.         'iterate through each row and import them into
  22.         'the table that you passed in by reference
  23.         Dim dbrow As DataRow
  24.         For Each dbrow In foundRows
  25.             mytable.ImportRow(dbrow)
  26.         Next
  27.  
  28.         'finally clear the contents of the tablecopy you created.
  29.         tablecopy.Clear()
  30.  
  31.     End Function