[RESOLVED] DataTable Sorting
Hi All,
I am creating a Datatable in memory from several sources. and need to order the data after I've build the Datatable before using it.
I need to order the table by 4 columns and thought that by doing :
Code:
resultTable.DefaultView.Sort = "Column1, Column2, Column3, Column4";
Would do the trick, it appears not to order them, but I do nto receive an error either.
Re: [RESOLVED] DataTable Sorting
Is this resolved ? if so please share your solution for others to use
Re: [RESOLVED] DataTable Sorting
What he posted should have worked just fine.
Re: [RESOLVED] DataTable Sorting
My guess is that the OP was expecting that code to sort the actual DataTable, as opposed to the DefaultView. If the DataTable is bound then the control(s) will display the sorted data because it comes from the DefaultView when binding. In code, you'd have to actually loop through the DefaultView rather than the DataTable itself.
Re: [RESOLVED] DataTable Sorting
as Lord_rat said, this does work, my problem was that the sort is only set against the DefaultView NOT the underlying dataset that I actually want to work with, to work behind the scenes with a sorted resulttable I needed to do:
Code:
DataRow[] SortedRow = resultTable.Select(null, "Col1, col2, col3, col4, ASC", DataViewRowState.CurrentRows);
The key here is passing null as the first parameter, it means I keep all my data. I then did the following to get the data back into my dataset:
Code:
for (int i = 0; i < SortedRow.Count(); i++)
{
tempTable.ImportRow(SortedRow[i]);
}
Re: [RESOLVED] DataTable Sorting
Quote:
Originally Posted by
Bill Crawley
to work behind the scenes with a sorted resulttable I needed to do:
No you didn't. You've already got a sorted result set. You just sorted the DefaultView so, if you want to access the sorted data, you do so using the DefaultView.
vb.net Code:
For Each row As DataRowView In myDataTable.DefaultView
MessageBox.Show(row("SomeColumn").ToString())
Next
If you really want a DataTable for some reason then the DefaultView, which is a DataView, has a method for that:
vb.net Code:
Dim newTable As DataTable = oldTable.DefaultView.ToTable()