How to Paging GridView in Asp.Net C# VB.Net

GridView paging will be required when data volume is higher. If you are using SqlDataSource control to bind a gridview control then no need to paging gridview because you will achieve it automatically. But if you use different datasource then you need to do mannual paging. To enable paging in gridview control at first set the AllowPaging=”true” and also define the page size by PageSize=”n”. In asp.net paging is too much easy. You just need to set the NewPageIndex on the PageIndexChanging event. The ultimate output of my below example looks like:

GridView paging manually in Asp.net CSharp VB.Net

Design the GridView for Paging like Below:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" />
             <asp:BoundField DataField="Size_gm" HeaderText="Size" />
             <asp:BoundField DataField="Price" HeaderText="Price" />
             <asp:BoundField DataField="ManufactureDate" HeaderText="Manufacture Date" />
             <asp:BoundField DataField="ExpireDate" HeaderText="Expire Date" />
         </Columns>
        </asp:GridView>

To Complete the Example We need to Create a DataBase Table:

CREATE TABLE [dbo].[Product](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
	[Size_gm] [int] NOT NULL,
	[Price] [numeric](18, 2) NOT NULL,
	[ManufactureDate] [smalldatetime] NOT NULL,
	[ExpireDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Insert some Data into the Database Table:

INSERT INTO Product Values(1,'Fair & Lovely',250,75,'Aug 04, 2014','Aug 04, 2015')
INSERT INTO Product Values(2,'Dove Soap',250,75,'Aug 02, 2014','Aug 04, 2015')
INSERT INTO Product Values(3,'Sunsilk',250,75,'Aug 07, 2014','Aug 04, 2015')
INSERT INTO Product Values(4,'Matador',250,75,'Jul 04, 2014','Aug 04, 2015')
INSERT INTO Product Values(5,'Colgate',250,75,'Jan 04, 2014','Aug 04, 2015')
INSERT INTO Product Values(6,'Lux Soap',250,75,'Feb 04, 2014','Aug 04, 2015')
INSERT INTO Product Values(7,'Meril Fresh Gel',250,75,'Aug 14, 2014','Aug 04, 2015')
INSERT INTO Product Values(8,'Tibbet Pomed',250,75,'Aug 24, 2014','Aug 04, 2015')

Now need to configure Web.Config File:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now under page load event first bind the data with the GridView and then cache the datasource which we will use to rebind when page index change. Note that it’s mandatory that’s why we use cache to preserve data.

Sample code is given below:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT * FROM Product Order BY Name";

            string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }
            
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["Data"] = dt;
        }
    }

VB.Net Code:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim dt As DataTable
            Dim SQL As String = "SELECT * FROM Product Order BY Name"

            Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Using conn As SqlConnection = New SqlConnection(sConstr)
                Using comm As SqlCommand = New SqlCommand(SQL, conn)
                    conn.Open()
                    Using da As SqlDataAdapter = New SqlDataAdapter(comm)
                        dt = New DataTable("tbl")
                        da.Fill(dt)
                    End Using
                End Using
            End Using


            GridView1.DataSource = dt
            GridView1.DataBind()
            Cache("Data") = dt
        End If
    End Sub

Now we need to set pages under GridView PageIndexChanging Event:
C# Code:

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = (DataTable)Cache["Data"];
        GridView1.DataBind();
    }

VB.Net Code:

    Protected Sub GridView1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
        GridView1.PageIndex = e.NewPageIndex
        GridView1.DataSource = CType(Cache("Data"), DataTable)
        GridView1.DataBind()
    End Sub

Now run the project, hope you will get paging enabled GridView.

Note: GridView control gives us PagerSettings tag to enrich look & feel for paging navigation. By using this PagerSettings tag you can navigate from one page to another by image or text instead of default number. To use images as your navigation just use FirstPageImageUrl, LastPageImageUrl, NextPageImageUrl, PreviousPageImageUrl properties.

Now modify the GridView control like below:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" />
             <asp:BoundField DataField="Size_gm" HeaderText="Size" />
             <asp:BoundField DataField="Price" HeaderText="Price" />
             <asp:BoundField DataField="ManufactureDate" HeaderText="Manufacture Date" />
             <asp:BoundField DataField="ExpireDate" HeaderText="Expire Date" />
         </Columns>

          <PagerSettings 
            Position="Bottom" 
            Mode="NextPreviousFirstLast" 
            FirstPageText="First" 
            LastPageText="Last" 
            NextPageText="Next" 
            PreviousPageText="Prev"
             />

        </asp:GridView>

Now you will get below output:
GridView paging manually in Asp.net CSharp VB.Net_2

Keep experimenting on PagerSettings tag to give the user different look and feel. Later i will discuss on efficient paging. Until then TC.

Download Code Example C#        Download Code Example VB.Net

Tagged with: , , ,
Posted in .Net, Asp.net, C#, Gridview, VB.Net
3 comments on “How to Paging GridView in Asp.Net C# VB.Net
  1. Omid says:

    tnx a million. very useful article.

  2. Rinku says:

    thts nice idea to catch datable.thnks alot πŸ™‚

  3. Sergio says:

    very useful samples thanks a lot

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*