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:
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:
Public Function SortTable(ByRef mytable As DataTable, ByVal column As String)
'Sorting a table for reals! By SiLentThReaD, AKA Numbchucks.
'create a blank table. tablecopy is the name
Dim tablecopy As New DataTable
'make an exact copy of the table you passed in by reference, and
'store it in your tablecopy table
tablecopy = mytable.Copy()
'clear the contents of the table you just passed in, because
'you will soon fill it with newly sorted rows
mytable.Clear()
'create a rows array
Dim foundRows() As DataRow
'assign the foundrows array the values returned
'from the select. In this case, I left the
'filterexpression blank, because I want to get
'everything. I all I need to change is the sort
'order.
foundRows = tablecopy.Select("", column + " asc")
'iterate through each row and import them into
'the table that you passed in by reference
Dim dbrow As DataRow
For Each dbrow In foundRows
mytable.ImportRow(dbrow)
Next
'finally clear the contents of the tablecopy you created.
tablecopy.Clear()
End Function