Is there a way to sort a data table and keep the new sorted order permanent? I'm using the data table to populate a treeview, and the data is already in the table, but I want it sorted by a certain column. Can you help? Thanks!
Printable View
Is there a way to sort a data table and keep the new sorted order permanent? I'm using the data table to populate a treeview, and the data is already in the table, but I want it sorted by a certain column. Can you help? Thanks!
Try
DataTable.DefaultView.Sort = "col1 ASC"
you can use multiple columns and go ASC or DESC.
Thank you, that helps reorder the grid view, but I found out that it does not change the actual row order. For example, if I originally had this table:
row# | id-field
0 | 3
1 | 2
2 | 1
and I use DataTable.DefaultView.Sort = "col1 ASC", the grid view will now show
row# | id
0 | 1
1 | 2
2 | 3
but in the actual table, if I access row #0's id field, it will still be 3, not 1.
VB Code:
Console.WriteLine("BEFORE " & ds.Tables(0).Rows(2).Item("id")) ds.Tables(0).DefaultView.Sort = "id DESC" Console.WriteLine("AFTER " & ds.Tables(0).Rows(2).Item("id"))
Output for both BEFORE and AFTER will be the same number. Is there anyway to make these sorted changes permanent, as in reassigns row#s. Thanks!!
I'm having the exact same problem.
Sorting my table visually works (it looks sorted) ... but when I try to access data from the newly sorted table, workrow = dtTable1.Rows(0) doesn't grab the 1st row in my newly sorted table ... it still grabs the old 1st row.
I've spent hours trying to resolve this .... but with no luck.
I think I've come to the conclusion that I need to use a DataView, but that wasn't working either.
Can anyone shed some light?
Thanks,
beaker
It is not possible to change the order of rows in a DataTable without actually removing them and then re-adding in the order you desire. The DefaultView property of a DataTable is a DataView object. When you bind a control to a DataTable, it is actually the DefaultView that determines what is displayed. If you set the RowFilter, RowStateFilter or Sort property of the DefaultView, the actual DataTable itself is unaffected, but if you iterate over the rows in the DataView you will find that they reflect the change. Note that a DataView is similar to a DataRowCollection, which is the type of the Rows property of a DataTable. A DataView contains DataRowView objects, which are similar but not quite the same as DataRow objects.
Edit:
To sum this up, the rows of a DataTable's DefaultView property will always correspond to the data displayed in a bound DataGrid. If you sort the DataView, the change is reflected in the DataGrid. If you sort the DataGrid by clicking on a column header, the change is reflected in the DataView. The underlying DataTable is affected by edits, i.e. inserting, updating or deleting rows, but not by sorting or filtering.