Luckily in .Net we can inherit classes, so it is not hard to implement a custom sort feature. here is how I did this:
Expand|Select|Wrap|Line Numbers
- Public Class SortableDataTable
- Inherits DataTable
- Public Sub Sort(ByVal columnIndex As Integer, _
- ByVal direction As dDir)
- Dim result As New List(Of DataRow)
- Select Case direction
- Case dDir.Ascending
- Dim v = From r In Me.Rows _
- Order By r(columnIndex) _
- Ascending
- For Each row In v
- Dim nr As DataRow = Me.NewRow
- nr.ItemArray = row.ItemArray.Clone
- result.Add(nr)
- Next
- Case dDir.Descending
- Dim v = From r In Me.Rows _
- Order By r(columnIndex) _
- Descending
- For Each row In v
- Dim nr As DataRow = Me.NewRow
- nr.ItemArray = row.ItemArray.Clone
- result.Add(nr)
- Next
- End Select
- Me.Rows.Clear()
- For Each row In result
- Me.Rows.Add(row)
- Next
- End Sub
- Public Sub New(ByVal source As DataTable)
- If Me.Columns.Count <> source.Columns.Count Then
- For Each c As DataColumn In source.Columns
- Me.Columns.Add(c.Caption)
- Next
- End If
- For Each r As DataRow In source.Rows
- Dim nr As DataRow = Me.NewRow()
- nr.ItemArray = r.ItemArray.Clone
- Me.Rows.Add(nr)
- Next
- End Sub
- End Class
- Public Enum dDir
- Ascending = 0
- Descending = 1
- End Enum
Expand|Select|Wrap|Line Numbers
- Public Sub Button1_Click(sender as object, e as EventArgs)
- Dim newTable As New SortableDataTable(oldTable)
- newTable.Sort(0, dDir.Ascending);
- End Sub
On a last note, I must admit there are probably easier ways to get this type of sorting implemented, however having an inherited class like this opens the possibility of advanced sorting.
Thanks for reading, and I hope it helps someone like it helped my colleague :)