tags:

views:

163

answers:

2

Hi,

I have a DataTable with 10 rows say one of the columns numbered 1 to 10 randomly. I want to sort them. usually, I do this:

DataView Dv = new DataView(dtPost, "", "views desc", DataViewRowState.Unchanged);
repeater.DataSource = Dv;
repeater.DataBind();

Now, I just want to bind the top 5 rows in this Dataview. If I try this:

DvPopBlogs.Table.Rows.Cast<System.Data.DataRow>().Take(5);

OR

DvPopBlogs.Table.AsEnumerable().Take(5); //this usually works if sorting wasnt necessary

It works, but the dataView completely forgets about the sorting and just selects 5 rows from top.

I have tried it with all DataViewRowStates too. How to select top 5 rows after sorting?

I seem to run out of ideas! please help!

+1  A: 

You are accessing the DataView, but then asking for the Table it is bound to - the table itself isn't sorted, the DataView provides a sorted "view" of the table.

So try (warning drycode!)

DvPopBlogs.DataViewRows.Take(5)

To get the first 5 (in sort order) DataViewRows. If you want the DataRows:

DvPopBlogs.DataViewRows.Take(5).Select(dvr => dvr.Row)

It's quite possible the enumerator from DataView is the DataViewRows collection, so you may be able to just use DvPopBlogs.Take(5).... if you wish.

Philip Rieck
yea, I found this out when I was trying to debug, dataview seemed to have sorted order but as soon as I added Table, the sort order was lost, now I understand table is the original data. thanks. But, DvPopBlogs is a DataView and it neither has .Take() or .DataViewRows() methods!
iamserious
Try either dvPopBlogs.AsEnumerable().Take, or in the worst case dvPopBlogs.ToTable() The latter will create a new DataTable from the contents of the view.
Philip Rieck
Hi, sorry, if I use the .ToTable() method repeater is complaining (on bind) that certain column doesnt exists. Debugging shows that it does exist, may be I am doing something wrong and I am sure you cant find out without the complete code. What do you suggest that I do now? Thanks, and sorry for asking too many questions!
iamserious
thanks, I actually figured out that this works, I had a small error in my code and I was barking up at the wrong tree from five days! I'm an idiot!
iamserious
A: 

Since you are casting already to a generic list, why not cast the dataview instead of the datatable?

IEnumerable<DataRow> sortedRows = DvPopBlogs.Cast<DataRowView>().Take(5).Select(r => r.Row);
Peter
Hi, its still throwing the same error, that one of the column doesn't exist! I have tried to debug it and I can clearly see the column, however, on databind it does throw this error!
iamserious
Hi, I'm an idiot, I Was looking at the wrong repeater from five days! this works, thanks!
iamserious