Click here to Skip to main content
15,886,095 members
Articles / Web Development / ASP.NET

Custom paging with ASP.NET GridView

Rate me:
Please Sign up or sign in to vote.
4.69/5 (29 votes)
26 Jun 2012CPOL2 min read 182.1K   4.3K   37  
Easy way to implement ASP.NET GridView paging .
///Auther:    Tanweer Akhtar
///Date:      26-06-2012
///Email:     tanweer_bravi@yahoo.com
///License    Copyright@tanweerbravi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int size = 0; int index = 0;

        if (!Page.IsPostBack)
        {
            //set the page size and current page number here, default is 10 and 1 respectively
            size = string.IsNullOrEmpty(Request["Size"]) ? 10 : Convert.ToInt32(Request["Size"]);
            index = string.IsNullOrEmpty(Request["Index"]) ? 1 : Convert.ToInt32(Request["Index"]);
            //load data from database
            BindGrid(size, index);

            //////////////////////////////////////////////////////
            if (size == 10)
                A1.Attributes.Add("class", "page-numbers current");
            else if(size==15)
                A2.Attributes.Add("class", "page-numbers current");
        }
    }
    void BindGrid(int size, int index)
    {
        //page url--get from Web.config file--------change it as your page URL
        string url = ConfigurationManager.AppSettings["URL"].ToString();
        //string templates for links
        string link = "<a  href='" + url + "?Index=##Index##&amp;Size=##Size##'><span class='page-numbers'>##Text##</span></a>";
        string link_pre = "<a href='" + url + "?Index=##Index##&amp;Size=##Size##'><span class='page-numbers prev'>##Text##</span></a>";
        string link_next = "<a href='" + url + "?Index=##Index##&amp;Size=##Size##'><span class='page-numbers next'>##Text##</span></a>";
        try
        {
            //the connectionstring from Web.config file--------change it as per your database settings
            String ConnStr = ConfigurationManager.ConnectionStrings["myConnection"].ToString();
            //the sql query with paging logics
            //here table name is "Orders" change this name as your requirement.
            //"CustomerID" is the column by which you can sort the records, change it as per your requirement
            String SQL = @"select * from (SELECT  ROW_NUMBER() OVER (ORDER BY CustomerID asc) as row,* FROM Orders) tblTemp
                        WHERE row between (" + index + " - 1) * " + size + " + 1 and " + index + "*" + size + " ";
            SQL += " select COUNT(*) from Orders";
            //fetching data from database suing SqlDataAdapter Fill method to bind the Gridview
            SqlDataAdapter ad = new SqlDataAdapter(SQL, ConnStr);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            //bind the grid with the ist data table---------remember that this dataset consist of two data tables
            this.gvPaging.DataSource = ds.Tables[0];
            this.gvPaging.DataBind();
            ////////get the n number of record///////////
            Double n = Convert.ToDouble(Convert.ToInt32(ds.Tables[1].Rows[0][0]) / size);
            /////////setting page numbers with links
            if (index != 1)
                lblpre.Text = link_pre.Replace("##Size##", size.ToString()).Replace("##Index##", (index - 1).ToString()).Replace("##Text##", "prev");
            else
                lblpre.Text = "<span class='page-numbers prev'>prev</span>";
            if (index != Convert.ToInt32(n))
                lblnext.Text = link_next.Replace("##Size##", size.ToString()).Replace("##Index##", (index + 1).ToString()).Replace("##Text##", "next");
            else
                lblnext.Text = "<span class='page-numbers next'>next</span>";
            //generate dynamic paging 
            int start;
            if (index <= 5) start = 1;
            else start = index - 4;
            for (int i = start; i < start + 7; i++)
            {
                if (i > n) continue;
                //create dynamic HyperLinks 
                HyperLink lnk = new HyperLink();

                lnk.ID = "lnk_" + i.ToString();
                if (i == index)//current page
                {
                    lnk.CssClass = "page-numbers current";
                    lnk.Text = i.ToString();
                }
                else
                {
                    lnk.Text = i.ToString();
                    lnk.CssClass = "page-numbers";
                    lnk.NavigateUrl = url + "?Index=" + i + "&Size=" + size + "";
                }
                //add links to page
                this.pl.Controls.Add(lnk);
            }
            //------------------------------------------------------------------
            //set up the ist page and the last page
            if (n > 7)
            {
                if (index <= Convert.ToInt32(n / 2))
                {
                    lblLast.Visible = true;
                    lblIst.Visible = false;
                    lblLast.Text = link.Replace("##Index##", n.ToString()).Replace("##Size##", size.ToString()).Replace("##Text##", n.ToString());
                    spDot2.Visible = true;
                    spDot1.Visible = false;
                }
                else
                {
                    lblLast.Visible = false;
                    lblIst.Visible = true;
                    lblIst.Text = link.Replace("##Index##", (n - n + 1).ToString()).Replace("##Size##", size.ToString()).Replace("##Text##", (n - n + 1).ToString());
                    spDot2.Visible = false;
                    spDot1.Visible = true;
                }
            }
        }
        catch (Exception ee)
        {
            //catch the exception
        }
    }


}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer LIFELONG Pakistan, Islamabad
Pakistan Pakistan
Software Engineer at LIFELONG Pakistan,

http://tanweerbravi.blogspot.com

Comments and Discussions