tags:

views:

66

answers:

3

I'm using LINQ to query my database, and I don't want all the records returned all at once. Instead, user should be able to select Next 5 and Previous 5 using buttons. As of this moment I have selected the first 5 rows in the Item table in the databas like this:

private void ShowItems()
{
    var items = (from p in db.Items
                 orderby p.ID descending
                 select new { ID = p.ID, Item = p.itemName, 
                     Qty = p.quantity }).Take(5);

    GridView.DataSource = items;
    GridView.DataBind();
}

So my idea was to change the Take() to something like Take(from, to), but it isn't supported. What do I do to solve my problem?

Thanx for listening!

+8  A: 

This should do it:

.Skip((pageNo - 1) * resultsPerPage)
.Take(resultsPerPage)
DaveShaw
Should be pageNo -1, fixed it.
Jan Jongboom
I noticed - I just added the comment to say "Assuming page 0" - I'll take it back out ;)
DaveShaw
+2  A: 

You can use the Skip and Take methods to achieve what you want.

madcapnmckay
+2  A: 
public static IEnumerable<T> Take<T>(this IEnumerable<T> collection, int start, int end)
{
    if (start > end) 
        throw new ArgumentException("Invalid parameters");
    return collection.Skip(start).Take(end - start);
}
Danny Chen