Once I wrote a class to make paging calculations. I had some data bound user controls that had no paging support. So I had to improvise. As it is was pointless to duplicate pager code to every user control where I needed paging I wrote a class to make my life easier.
/// <summary>
/// Class for data pager calculations.
/// </summary>
public class Pager
{
/// <summary>
/// Number of current page.
/// </summary>
public int CurrentPage = 1;
/// <summary>
/// Number of previous page.
/// </summary>
public int PreviousPage = 1;
/// <summary>
/// Number of next page.
/// </summary>
public int NextPage = 1;
/// <summary>
/// Count of pages.
/// </summary>
public int PageCount = 1;
/// <summary>
/// Page's first row index in collection.
/// </summary>
public int StartRow = 0;
/// <summary>
/// Pages last row index in collection plus one.
/// It is meant to use in for loop.
/// </summary>
public int StopBeforeRow = 0;
/// <summary>
/// Returns pager object with values based on given parameters.
/// </summary>
/// <param name="pageNo">Number of current page.</param>
/// <param name="pageSize">Page size.</param>
/// <param name="collectionSize">Size of rows or items collection.</param>
/// <returns></returns>
public static Pager GetPager(int pageNo, int pageSize, int collectionSize)
{
Pager pg = new Pager();
pg.CurrentPage = pageNo;
pg.PageCount = (int)Math.Ceiling((double)collectionSize / pageSize);
if (pg.CurrentPage > pg.PageCount)
pg.CurrentPage = pg.PageCount;
if (pageNo > 1)
pg.PreviousPage = pg.CurrentPage - 1;
else
pg.PreviousPage = 1;
if (pg.CurrentPage >= pg.PageCount)
pg.NextPage = pg.PageCount;
else
pg.NextPage = pg.CurrentPage + 1;
pg.StartRow = (pg.CurrentPage - 1) * pageSize;
pg.StopBeforeRow = pg.CurrentPage * pageSize;
if (pg.StopBeforeRow > collectionSize)
pg.StopBeforeRow = collectionSize;
return pg;
}
}
As you can see this class takes also care of inconsistent parameters and handles them so your code doesn’t stop working.
View Comments (2)
I am new to this. How do I impliment this class
ager pager = Pager.GetPager(currentPage, 10, myTable.Rows.Count);