sorting a DataTable

  • Thread starter Thread starter Bob
  • Start date Start date
B

Bob

I need to sort the contents of a DataTable by a column *after* it's been
populated. Is this possible?

Bob
 
I need to sort the contents of a DataTable by a column *after* it's been
populated. Is this possible?


You can apply a Dataview to the DataTable. Or you can issue a
datatable.select and order it via that way as well.
 
Hi Bob,

dim dv as new dataview(myDatatable)
dv.sort = "mysortcolumn"

You can access the dv a little bit the same as the datatable.

I hope this helps,

Cor
 
Actually, tables in a have a default view. This is normally presented for
example to a DataGrid's DataSource.

Ds1.Tables(0).DefaultView.Sort = "LastName"

Regards - OHM


--

OHM ( Terry Burns )
. . . One-Handed-Man . . .

Time flies when you don't know what you're doing
 
I need the row indexes in a particular order, TBD after population. Will I
just have to create a new DataTable?

Bob
 
Private Sub SortTable(ByVal dt As DataTable, ByVal col As DataColumn)
Dim SortValues(dt.Rows.Count - 1) As Object
Dim SortIndex(dt.Rows.Count - 1) As Integer
For i As Integer = 0 To dt.Rows.Count - 1
SortIndex(i) = i
SortValues(i) = dt.Rows(i)(col)
Next
System.Array.Sort(SortValues, SortIndex)
For i As Integer = 0 To SortIndex.GetUpperBound(0)
dt.ImportRow(dt.Rows(SortIndex(i)))
Next
For i As Integer = 0 To SortIndex.GetUpperBound(0)
dt.Rows.RemoveAt(0)
Next
End Sub
 
Hi Bob,

Is this not more simple?
\\\
Dim dv As New DataView(dt)
dv.Sort = "bla"
Dim dtnew As DataTable = dt.Clone
For Each dvr As DataRowView In dv
dtnew.ImportRow(dvr.Row)
Next
///

Cor
 
Bob,
In addition to Cor's suggestion of using the DataView to sort.

You can use DataTable.Clear to remove all the rows.

dt.Clear()

Hope this helps
Jay
 
Yes, certainly. But I ran into the problem of already having variables
pointing to columns in the original table so I couldn't use a newly created
one. I would definitely use your solution otherwise.

Bob
 
Back
Top