Paging in ASP.Net GridView in Code Behind using C#

Introduction

In this article, I will explain how to Implement Paging in ASP.Net GridView in Code Behind using C#. For this demo purpose, I am using visual studio 2012 and Microsoft SQL Server 2008 r2. So, before opening visual studio let’s create and populate student table using following script.

Student table script

Create table tblstudent
(
Id int,
NAME varchar(50),
CITY varchar(50),
)
Insert into tblstudent values(1,'Sara','Mumbai')
Insert into tblstudent values(2,'David','Boston')
Insert into tblstudent values(3,'Dora','New York')
Insert into tblstudent values(4,'Vikram','Bali')
Insert into tblstudent values(5,'Nikhil','Paris')
Insert into tblstudent values(6,'John','London')
Insert into tblstudent values(7,'Michael','Chennai')
Insert into tblstudent values(8,'Sam','London')
Insert into tblstudent values(9,'Maya','New york')
Insert into tblstudent values(10,'Dimple','Delhi')
Insert into tblstudent values(11,'John','London')
Insert into tblstudent values(12,'Sara','Sydeny')
Insert into tblstudent values(13,'Vikram','Delhi')
Insert into tblstudent values(14,'Twinkle','Sydeny')
Insert into tblstudent values(15,'David','')
Insert into tblstudent values(16,'John','Dubai')
Insert into tblstudent values(17,'Lincoln','Singapore')
Insert into tblstudent values(18,'jack','Delhi')

Let’s start for this demo step by step using ‘Asp.Net Empty Web Application’.

Step 1: Create Asp.Net project, by using following steps.

  1. Open Visual Studio.
  2. Click on File -> New -> Project.
  3. In this project, I am using C# as a programming language, but you can also choose VISUAL BASIC if you know syntaxes of VB.
  4. Inside Visual C# -> Web -> Select Asp.Net Empty Web Application -> Name your project as GridViewPaging -> Select Ok

Step 2: Add index.aspx file inside solution explorer.

  1. Copy and paste following code in between form element of your index.aspx. In Here I have drag and drop gridview control from toolbox to index.aspx file.
  2. The HTML code consists of an ASP.Net GridView with 3 BoundField columns. In order to implement Paging in GridView, AllowPaging property is set to true, OnPageIndexChanging event has been handled & gridview pagesize set to 5.
<div>
    <h2>Paging in ASP.Net GridView in Code Behind using C#</h2>

    <asp:gridview ID="Gridview1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
    OnPageIndexChanging="OnPageIndexChanging" PageSize="5" >

    <Columns>
    <asp:BoundField ItemStyle-Width="150px" DataField="ID" HeaderText="ID" />
    <asp:BoundField ItemStyle-Width="150px" DataField="NAME" HeaderText="NAME" />
    <asp:BoundField ItemStyle-Width="150px" DataField="CITY" HeaderText="CITY" />
        
    </Columns>
    </asp:gridview>
</div>

Step 3: Connection string to connect front end visual studio and back end microsoft sql server 2008 R2. Add following code in web.config file of your project at the end of the configuration tag.

<connectionStrings>
    <add name="constr"
         connectionString="Server=localhost; Database=sample ; Integrated Security=True"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

Step 4: index.aspx.cs – behind code

  • Method to bind Gridview
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Select ID, NAME, City from tblstudent"))
        {
            using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sqlDataAdapter.SelectCommand = cmd;
                using (DataTable dataTable = new DataTable())
                {
                    sqlDataAdapter.Fill(dataTable);
                    Gridview1.DataSource = dataTable;
                    Gridview1.DataBind();
                }
            }
        }
    }
}

  • The following event handler is executed when a page is changed inside the GridView.
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    Gridview1.PageIndex = e.NewPageIndex;
    this.BindGrid(); 
}
  • Use bindgrid method on page load
protected void Page_Load(object sender, EventArgs e)
{
    BindGrid();
}
  • Do not forget to add following 2 namespaces, because all namespace which helps us to connect to SQL server is residing inside this namespace.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Step 4 : Press F5 and see result

List of students

Leave a Comment