views:

2447

answers:

5

I am confused on DataTable.DefaultView.Sort. Here is the segment of the code I want to use it in.

actionLogDT.DefaultView.Sort = "StartDate";

foreach (CustomerService.ActionLogStartEndRow logRow in actionLogDT)
{
  // code here
}

The samples I have seen don't use the foreach loop and thus is confusing me on how to process this. It isn't sorting as I thought it should be.

I see that .DefaultView returns a view, and .Table gives a compile error.

+3  A: 

Sorting the view won't change the sort order of the data in the table, just the order in the view. It should work if you do your foreach on the view instead, casting the row from the DataRowView back to your strongly typed row.

foreach (DataRowView logRowView in actionLogDT.DefaultView)
{
    CustomerService.ActionLogStartEndRow logRow = logRowView.Row as CustomerService.ActionLogStartEndRow;
    // code here
}
Jeromy Irvine
Doing that gives me an "Unable to cast object of type 'System.Data.DataRowView' to type 'ActionLogStartEndRow'." error.
Mike Wills
Does `ActionLogStartEndRow` derive from DataRow?
Jeromy Irvine
@Jeromy - I am sure it does. I am using the .XSD data layer to accomplish all of this.
Mike Wills
@Mike - In that case, my updated answer should work.
Jeromy Irvine
Basically the same casting error. Unable to cast object of type 'System.Data.DataRow' to type 'ActionLogStartEndRow'.
Mike Wills
OK, I updated the answer to account for the strongly typed row. This should hopefully do the trick for you.
Jeromy Irvine
+1  A: 
foreach (var logRow in actionLogDT.DefaultView.ToDataTable()) { ... }
John Sheehan
+1  A: 

I had to take a slightly different approach. This post was the closest I could find to get my code to work. Here is the working result:

actionLogDT.DefaultView.Sort = "StartDate";
DataView dv = actionLogDT.DefaultView;

foreach (DataRowView logRow in dv) { . . . }

From there I just have to cast the value back into it's proper type.

(string)logRow["Status"].ToString()
Mike Wills
A: 

Just curious: Why are you using the DataRowView?

i.e.

foreach (DataRow row in actionLogDT.Rows)
{
  Console.WriteLine(row["Status"]);
}
jp2code
I don't understand your question.
Mike Wills
Because the question was about sorting a datatable. To enumerate the sorted data you need to enumerate the view, not the table itself.
Stuart Hallows
+1  A: 

Please try this:

actionLogDT.DefaultView.Sort = "["+actionLogDT.Columns[0].ColumnName+"] asc";
Upender
I'll try that next time I have this problem.
Mike Wills