Skip to main content

Populate custom pagination for databind controls using custom paging in asp.net c#

This article explains how to make different - different type of pager (i.e. pagination links) with the given total row count, page size and current page index.

Recently i have posted custom paging in gridview using store procedure in asp.net c#, Paging in datalist databind control in asp.net, Importing data from excel 2003 (.xls) in to gridview in asp.net, Exporting gridview data into excel (.xls,.xlsx) file in asp.net c#
As we know when we use default paging in gridview, pager and pagination automatic create and maintain by asp.net we just need to change property for getting different type of pagination but when we are using custom paging in databind control then we need to generate pager manually and make a logic for populating different - different type of pagination so here is the some predefined nice pagination template logic.

Just use generatePager method and call it after binding your result data gridview and pass three parameter that is total row count , page size and current page index.

Generate pager with whole page links, next and previous button -


public void generatePager(int totalRowCount, int pageSize, int currentPage)
{
    int totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

    List<ListItem> pageLinkContainer = new List<ListItem>();

    pageLinkContainer.Add(new ListItem(" << Previous << ", (currentPage - 1).ToString(), currentPage > 1));
    for (int i = 1; i <= totalPageCount; i++)
    {
        pageLinkContainer.Add(new ListItem(i.ToString(), i.ToString(), currentPage != i));
    }
    pageLinkContainer.Add(new ListItem(" >> Next >> ", (currentPage + 1).ToString(), currentPage < totalPageCount));

    dlPager.DataSource = pageLinkContainer;
    dlPager.DataBind();
}

Generate pager with whole page links, next and previous button.
Generate pager with whole page links, next and previous button demo

Generate page with 5 page links at a time and with first, last button -


public void generatePager(int totalRowCount, int pageSize, int currentPage)
{
    int totalLinkInPage = 5;
    int totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

    int startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
    int lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

    if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
    {
        lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
        startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
    }

    List<ListItem> pageLinkContainer = new List<ListItem>();

    if (startPageLink != 1)
        pageLinkContainer.Add(new ListItem("First", "1", currentPage != 1));
    for (int i = startPageLink; i <= lastPageLink; i++)
    {
        pageLinkContainer.Add(new ListItem(i.ToString(), i.ToString(), currentPage != i));
    }
    if (lastPageLink != totalPageCount)
        pageLinkContainer.Add(new ListItem("Last", totalPageCount.ToString(), currentPage != totalPageCount));

    dlPager.DataSource = pageLinkContainer;
    dlPager.DataBind();


Generate page with 5 page links at a time and with first, last button.
Generate page with 5 page links at a time and with first, last button  demo

Generate Pager with 5 links at a time, first, last, next and previous button -


public void generatePager(int totalRowCount, int pageSize, int currentPage)
{
    int totalLinkInPage = 5;
    int totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

    int startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
    int lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

    if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
    {
        lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
        startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
    }

    List<ListItem> pageLinkContainer = new List<ListItem>();

    pageLinkContainer.Add(new ListItem("First", "1", currentPage != 1));
    pageLinkContainer.Add(new ListItem(" << Previous << ", (currentPage - 1).ToString(), currentPage > 1));
    for (int i = startPageLink; i <= lastPageLink; i++)
    {
        pageLinkContainer.Add(new ListItem(i.ToString(), i.ToString(), currentPage != i));
    }
    pageLinkContainer.Add(new ListItem(" >> Next >> ", (currentPage + 1).ToString(), currentPage < totalPageCount));
    pageLinkContainer.Add(new ListItem("Last", totalPageCount.ToString(), currentPage != totalPageCount));

    dlPager.DataSource = pageLinkContainer;
    dlPager.DataBind();
}

Generate Pager with 5 links at a time, first, last, next and previous button.
Generate Pager with 5 links at a time, first, last, next and previous button demo

CommondArgument actually have the page index we have to find page index in click event and bind result grid , pager datallist again.

Html Part :

protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
{
   if (e.CommandName == "PageNo")
   {
       bindGrid(Convert.ToInt32(e.CommandArgument));
   }
}


<asp:DataList CellPadding="5" RepeatDirection="Horizontal" runat="server" ID="dlPager"
    onitemcommand="dlPager_ItemCommand">
    <ItemTemplate>
       <asp:LinkButton Enabled='<%#Eval("Enabled") %>' runat="server" ID="lnkPageNo" Text='<%#Eval("Text") %>' CommandArgument='<%#Eval("Value") %>' CommandName="PageNo"></asp:LinkButton>
    </ItemTemplate>
</asp:DataList>



Binding Grid Control Code :

public void bindGrid(int currentPage)
{
 int pageSize = 10;
 int _TotalRowCount = 0;

 string _ConStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
 using (SqlConnection con = new SqlConnection(_ConStr))
 {

   SqlCommand cmd = new SqlCommand("getDeals", con);
   cmd.CommandType = CommandType.StoredProcedure;

   int startRowNumber = ((currentPage - 1) * pageSize) + 1;
      
   cmd.Parameters.AddWithValue("@StartIndex", startRowNumber);
   cmd.Parameters.AddWithValue("@PageSize", pageSize);

   SqlParameter parTotalCount = new SqlParameter("@TotalCount"SqlDbType.Int);
   parTotalCount.Direction = ParameterDirection.Output;
   cmd.Parameters.Add(parTotalCount);

   SqlDataAdapter da = new SqlDataAdapter(cmd);
   DataSet ds = new DataSet();
   da.Fill(ds);

   _TotalRowCount = Convert.ToInt32(parTotalCount.Value);

   grdCustomPagging.DataSource = ds;
   grdCustomPagging.DataBind();

   generatePager(_TotalRowCount, pageSize, currentPage);

 }
}

<asp:GridView Width="500" runat="server" ID="grdCustomPagging">
</asp:GridView>



Popular posts from this blog

Uploading large file in chunks in Asp.net Mvc c# from Javascript ajax

Often we have a requirement to upload files in Asp.net, Mvc c# application but when it comes to uploading larger file, we always think how to do it as uploading large file in one go have many challenges like UI responsiveness, If network fluctuate for a moment in between then uploading task get breaks and user have to upload it again etc.

Regular expression for alphanumeric with space in asp.net c#

How to validate that string contains only alphanumeric value with some spacial character and with whitespace and how to validate that user can only input alphanumeric with given special character or space in a textbox (like name fields or remarks fields). In remarks fields we don't want that user can enter anything, user can only able to enter alphanumeric with white space and some spacial character like -,. etc if you allow. Some of regular expression given below for validating alphanumeric value only, alphanumeric with whitspace only and alphanumeric with whitespace and some special characters.

How to handle click event of linkbutton inside gridview

Recently I have posted how to sort only current page of gridview , Scrollble gridview with fixed header through javascript , File upload control inside gridview during postback and now i am going to explain how to handle click event of linkbutton or any button type control inside gridview. We can handle click event of any button type control inside gridview by two way first is through event bubbling and second one is directly (in this type of event handling we need to access current girdviewrow container)

regex - check if a string contains only alphabets c#

How to validate that input string contains only alphabets, validating that textbox contains only alphabets (letter), so here is some of the ways for doing such task. char have a property named isLetter which is for checking if character is a letter or not, or you can check by the regular expression  or you can validate your textbox through regular expression validator in asp.net. Following code demonstrating the various ways of implementation.