09/09/2014 by Nitesh

How To Implement Paging in GridView Control in ASP.Net

Friends,

GridView is one of the most common tools for displaying data in a grid format in Asp.Net. When the data becomes large, paging helps the users to view chunks of data and also increases Page load time. In this post, we will see how can we implement Paging in a GridView control.

So, lets dig directly into the code.

ASPX Page

  • In your Visual Studio solution, on any page drag and drop a GridView control.Lets name it as grdData.
  • Set the AllowPaging property of the GridView as true.
  • Handle the OnPageIndexChanging event of the GridView.
  • By default GridView displays 10 records per page. If you want to modify the number of records displayed per page, set the PageSize property of GridView to your desired number. In this example, I have set this property to 5.
  • Below is the complete GridView code in aspx page.

            
            
                
                
            
            
            
            
            
            
            
            
            
            
            
        
        

ASPX.CS Page

  • Create a new function that loads data from your data repository (database) and bind it to GridView. Lets name it as LoadGridData()
  • On Page_Load event, call the LoadGridData() after checking the IsPostback property of the page.
  • In the grdData_PageIndexChanging event, write the below code. In the below code, we are setting the NewPageIndex property of the GridView and calling the LoadGridData() fucntion again. .Net GridView automatically handles the internal stuff for displaying only the data for the selected Page.
  • Below is the complete code from .aspx.cs page
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadGridData();
        }

        private void LoadGridData()
        {
            //I am adding dummy data here. You should bring data from your repository.
            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");

            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = i + 1;
                dr["Name"] = "Student " + (i + 1);

                dt.Rows.Add(dr);
            }
            grdData.DataSource = dt;
            grdData.DataBind();
        }

        protected void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdData.PageIndex = e.NewPageIndex;
            LoadGridData();
        }

You’re done.

Output

Page 1:

Page1

Page 2:

Page2

Hope you like this! Keep learning and sharing! Cheers!

#ASP.Net#C##GridView