Search Engine style paging in asp.net(C#)

When a large number of records are to be displayed and total number of records is variable in nature then search engine style paging is the best approach. For a search query, we need to pass start record number and page size for paging. In the most search engine, the start index is passed using querystring.
See following, Google uses “start” query string parameter.

google paging
To create search engine style pagination in asp.net, see following method. It takes 3 parameters:
1. totalRecords
2. pageSize
3. totalNumericLinks : total number of numeric links. It is 20 in above image.
string GetPaging(int totalRecords, int pageSize, int totalNumericLinks)
{
if (totalRecords <= pageSize)
{
return "";
}

StringBuilder str = new StringBuilder();
//Get Total no of pages
int totalPages = totalRecords / pageSize + (totalRecords % pageSize > 0 ? 1 : 0);
//Get Current Page no
int currentPageNo = 1;
string pageUrl = Context.Request.Url.AbsolutePath;    
if (Context.Request.QueryString["start"] != null)
{
currentPageNo = 1 + (Convert.ToInt32(Context.Request.QueryString["start"]) - 1) / pageSize;           
}

//Add previous button
if (currentPageNo > 1)
{
str.Append(string.Format(" <a  href=\"" + pageUrl + "?start={0}\" title=\"Previous page\"><Prev</a>", (currentPageNo - 2)*pageSize + 1));
}
//Add Numeric link
int sp, ep;
if (totalNumericLinks >= totalPages)
{
sp = 1;
ep = totalPages;
}
else
{
if (currentPageNo - totalNumericLinks / 2 > 0)
{                    
ep = (currentPageNo + totalNumericLinks / 2 - (totalNumericLinks-1)%2);
ep = ep < totalPages ? ep : totalPages;
}
else
{                  
ep = totalNumericLinks;
}
sp = ep - totalNumericLinks+1 > 0?ep - totalNumericLinks+1:1;
}
for (int p = sp; p <= ep; p++)
{
//For Current Page, No Link, Bold Text  
if (p == currentPageNo)
{
str.Append(String.Format(" <b>{0}</b>", p.ToString()));
}
else
{
str.Append(String.Format(" <a href=\"" + pageUrl + "?start={1}\" title=\"{0}\">{0}</a> ", p, (p - 1) * pageSize + 1));
}
}
//Add Next button
if (currentPageNo < totalPages)
{
str.Append(String.Format(" <a href=\"" + pageUrl + "?start={0}\" title=\"Next page\">Next></a>", (currentPageNo * pageSize +1).ToString()));
}

return str.ToString(); 

}

Hope ! It helps.

No comments:

Post a Comment