Hi,

I'm trying to sort a DataTable using the following code:

Private Function sortDataTable(ByVal dTable As DataTable) As DataTable
        Dim dView As New DataView(dTable)
        dView.Sort = "Field ASC"

        Return dTable
End Function

But it doesn't work. What is wrong? How can I sort the DataTable?

Thanks,

Ana

Dani AI

Generated

Short diagnosis: created a view, applied a sort to that view, and then returned the original DataTable — so the caller never sees the sorted results. A DataTable does not automatically reorder its rows when you sort a DataView; the view presents rows in a sorted order, the underlying table’s physical row order is unchanged.

Options and when to use them:

  • Returning a DataView (as suggested) is fine when the consumer can work with a view.
  • For UI binding, using the table’s default view is simplest (this is what was pointing at).
  • If you must return a DataTable instance already sorted, create a new DataTable from the sorted rows (DataTable.Select + CopyToDataTable, or build a DataView and call ToTable).

Example (VB) — create a new sorted DataTable and handle empty results:

Private Function SortedCopy(ByVal src As DataTable, ByVal columnName As String, Optional ByVal ascending As Boolean = True) As DataTable
    Dim sortExpr As String = columnName & If(ascending, " ASC", " DESC")
    Dim rows() As DataRow = src.Select(Nothing, sortExpr)
    If rows.Length = 0 Then
        Return src.Clone() ' empty table with same schema
    End If
    Return rows.CopyToDataTable()
End Function

Notes and troubleshooting:

  • CopyToDataTable lives in System.Data.DataSetExtensions; add the assembly/reference if needed. It will throw if given an empty array, so guard as above.
  • ToTable/CopyToDataTable create a brand‑new table and may not preserve RowState or original row IDs. Use a DataView if you need live tracking of edits.
  • Verify the column name exists and its data type: strings sort lexicographically (so numeric strings will sort incorrectly unless converted).
  • For very large tables prefer sorting via DataView (presentation) rather than copying rows repeatedly for performance.
Member Avatar for Member #676683

try:

Private Function SortDataTable(ByVal dTable As DataTable, ByVal ColumnName As String, Optional ByVal OrderByAsc As Boolean = True) As DataView
Dim dView As New DataView(dTable)

If OrderByAsc Then
dView.Sort = ColumnName & " ASC"
Else
dView.Sort = ColumnName & " DESC"
End If

Return dView
End Function

Just sort the table directly:
dTable.DefaultView.Sort = ColumnName & " ASC"

commented: Please don't revive 3 year old SOLVED Threads. -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.