Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Guys,

I spent couple of hours in google looking for idea on how to implement paging/sorting in gridview in an optimize manner.

Database side:
make a query that will only get the number of records for display. (i am clear with this)


(Server Code):
Use ObjectContainerDatasource and mapped it to your gridview.


Question if i map it directly to the gridview isn't it bypassing the idea of MVP?
Any tips on how to achieve this?

appreciate any help.
thanks.
jepoy
Posted

1 solution

If all of your data will fit in available memory, you could retrieve all of the data you need to display, and then extract only the items that will fit in a page. Psuedo code:

0) retrieve data

1) Calculate number of pages you have - Math.Min(1, Math.Floor(records_retrieved / records_per_page)))

2) Extract the items. I'd probably write an extension method to do this, and then you can use it on any apprpopriately typed collection. The guts of the method would look something like this:


C#
List<T> result = new List<T>();
int skipItems = recsPerPage * (pageNumber - 1);
if (list.Count > skipItems)
{
    list.Skip(skipItems);
    result = list.Take(Math.Min(list.Count - skipItems, 100);
}
return result;


EDIT =====================

Here's some code that works:

C#
List<string> myStrings = new List<string>();
myStrings.Add("1");
myStrings.Add("2");
myStrings.Add("3");
myStrings.Add("4");
myStrings.Add("5");

// we want the 3rd page of data (with 1 item per page)
List<string> result = myStrings.GetPageOfData(3, 1);</string>


Here's the extension method:

C#
public static List<T> GetPageOfData<T>(this List<T> list, int pageNumber, int recsPerPage)
{
    List<T> results = new List<T>();
    int skipItems = recsPerPage * (pageNumber - 1);
    int itemsToReturn = Math.Min(list.Count - skipItems, recsPerPage) - 1;
    if (list.Count > skipItems)
    {
        for (int i = skipItems; i <= (skipItems + itemsToReturn); i++)
        {
            results.Add(list[i]);
        }
    } 
    return results;
}
 
Share this answer
 
v4
Comments
Jephunneh Malazarte 18-Jul-11 1:05am    
Hello john thanks for the solution.
I would like to ask if this algo works in grid view control?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900