Link to home
Create AccountLog in
Avatar of engg
engg

asked on

sorting Datatable using Dataview

I need to sort a datatable only once and then iterate through its rows multiple times (after postbacks, so I am using a cache to store the datatable).

       DataTable dt = null;
       DataView dv = ((DataTable)Cache[User.Identity.Name]).DefaultView;
       dv.Sort = "date";
       dt = dv.Table;

At this point, will the datatable 'dt' have sorted rows?

Another thing, does the following statement always return the rows of the datatable in the same order, if I use it multiple times?
      foreach (DataRow dr in dt.Rows)

I would prefer not to use this:
     foreach (DataRowView drv in dt.DefaultView).

Thanks.
Avatar of raterus
raterus
Flag of United States of America image

The DataView does not modify any data in the DataTable, it's truly just a "View" of your DataTable.

You should definitely iterate over the DataTable and not the DataView if you are concerned about the order.
Avatar of engg
engg

ASKER

Thanks.

1)
DataTable dt = null;
DataView dv = ((DataTable)Cache[User.Identity.Name]).DefaultView;
dv.Sort = "date";
dt = dv.Table;

At this point, would the datatable 'dt' contain data sorted by date?


2)
If I call  this statement multiple times, will it always return the data in the datatable in the same order?
foreach (DataRow dr in dt.Rows)
{
.....
}
ASKER CERTIFIED SOLUTION
Avatar of raterus
raterus
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of engg

ASKER

Thank you.
1) I didn't want to have an overhead of creating a new sorted table. But I think that's the only option.

2) Good. Because I thought if it works like a select query in SQL, it doesn't have to return the data in the same order.

I will get back soon.