DefaultView Sort not sorting rows...

forgottensoul

Member
Joined
Nov 16, 2004
Messages
17
I have created a view using the DefaultView.Sort property. If I bind this data to a data grid I can see the data is sorted. If I loop through each of the rows, the rows are not sorted.

Is there a way to sort the DataView so that the rows are sorted?
C# code
Code:
DataView tmp = myData.Tables["ATable"].DefaultView;
tmp.Sort = "SomeColumn";
dataGridView1.DataSource = tmp.Table;

// Loop through each row in the tmp var. They are not sorted, 
// but the data grid is.
foreach (DataRow currentRow in tmp.Table.Rows)
{
   string rowCol1 = currentRow[1].ToString();
}

The rows returned in the loop are not sorted. The datagrid on my forum is. Any ideas on how to get a loop through the rows that would be sorted?

Thank you,
 
I also tried setting the sort order before assigning it to my temp var. No luck.

According to the MSDN lib
Filtering and Sorting in Datasets

You can use a data view (DataView object). A data view is an object that acts as a layer on top of the data table, providing a filtered and sorted view of the tables contents.

Must be something simple I am doing wrong or is binding the data the only way to see the sorted view?
 
After spending time looking through docs and testing out "guesses", I now believe that you can use the default view and table object to show sorted values. Only the original order of the data.

If you want to see the sorted values you have to either "Select" the data into data rows or bind them to an object such as the grid. This doesnt seem right to be me, but at least working that way I can get the code moving again.
 
Hello!

Im facing the exactly same problem here...its getting very frustrating as a matter of fact! What in the world is the use of this "Sort" property of the datatables defaultview if it does not sort the rows? If someone find it out, please post the explanation here...

:mad:
 
Have you tried using the DataView object as the data source and as the variable you iterate over rather than its table property?

e.g.
C#:
DataView tmp = myData.Tables["ATable"].DefaultView;
tmp.Sort = "SomeColumn";
dataGridView1.DataSource = tmp;

// Loop through each row in the tmp var. They are not sorted, 
// but the data grid is.
foreach (DataRow currentRow in tmp)
{
   string rowCol1 = currentRow[1].ToString();
}
 
Finally!

Thank you! Your solution is fine!

My mistake when accessing the DataView was: DataTable.DefaultView.Table.Rows[line][column]...you see, DataTable.DefaultView.Table.Rows is the same of DataTable.Rows. Once youve sorted the DefaultView you must access it as showed by "PlausiblyDamp" (by looping through the DefaultView rows)

foreach (DataRowView currentRow in tmp)
{
string rowCol1 = currentRow[1].ToString();​
}

Thank you again "PlausiblyDamp".
 
Back
Top