• Default Paging in ASP.NET GridView Control

    Posted on March 30, 2012 by in ASP.NET, C#, Dotnet

    The ASP.NET GridView control has a built-in paging capability that supports basic paging functionality. You can use the default paging user interface (UI) or create a custom paging interface. In this article, I would be discussing about the former one i.e. default paging. You could implement default paging in more than one way, but in my discussion the GridView control is bound to a data structure in code through the DataSource property. GridView control will perform paging by getting all of the data records from the source, displaying only the records for the current page, and discarding the rest.

    Database Connection

    Open web.config and add following entry to connection strings element

    <add name="Sql" connectionString="Data Source=<SERVERNAME>;
         Initial Catalog= TEST;User=testuser;Password=testuser;" 
         providerName="System.Data.SqlClient"/> 

    Page Design

    First & foremost thing we have to do is to enable default paging and set the page size.

    <asp:gridview ID="gvProducts" PageSize="5" AllowPaging="True"

    When user clicks one of the pager buttons is clicked, PageIndexChanging event is raised. We have to implement this event handler. Since it occurs before the GridView control handles the paging operation, we need to set the new page index to the grid and rebind the data as it is a postback.

    <asp:gridview ID="gvProducts" 
                    PageSize="5" AllowPaging="True"
                    OnPageIndexChanging="gvProducts_PageIndexChanging">   
    
    protected void gvProducts_PageIndexChanging(object sender, 
    GridViewPageEventArgs e)
    {
        gvProducts.PageIndex = e.NewPageIndex;
        BindData();
    }
    

    Since we set the AllowPaging property of the GridView control to true, the GridView control automatically adds user interface (UI) controls for paging. We can customize the UI for paging by adding a PagerTemplate template. To specify which paging operation to perform, include a LinkButton control with its CommandName property set to Page and a CommandArgument set to one of the following values:

    • First To move to the first page.
    • Last To move to the last page.
    • Prev To move to the previous page.
    • Next To move to the next page of data
    <PagerTemplate>
      <table>
        <tr>                      
          <td><asp:LinkButton ID="FirstButton" CommandName="Page" 
    CommandArgument="First" Text="First" RunAt="server"/></td>
          <td><asp:LinkButton ID="PrevButton"  CommandName="Page" 
    CommandArgument="Prev"  Text="Previous"  RunAt="server"/></td>
          <td><asp:LinkButton ID="NextButton"  CommandName="Page" 
    CommandArgument="Next"  Text="Next"  RunAt="server"/></td>
          <td><asp:LinkButton ID="LastButton"  CommandName="Page" 
    CommandArgument="Last"  Text="Last" RunAt="server"/></td>
        </tr>
      </table>
    </PagerTemplate>
    

    If you put everything together, we have our complete page design. I have added some cosmetic stuff to make it look nice, nothing fancier though.

    <asp:gridview ID="gvProducts" 
            PageSize="5" AllowPaging="True"
            BorderColor="White" BorderStyle="Ridge"
            CellSpacing="1" CellPadding="3" GridLines="None" 
            BackColor="White" BorderWidth="2px"
            AutoGenerateColumns="False" AllowSorting="True"                            
            runat="server" DataKeyNames="ProductID"
            OnPageIndexChanging="gvProducts_PageIndexChanging">          
        <Columns>
            <asp:BoundField DataField="ProductID" HeaderText="Product ID">  
                <HeaderStyle HorizontalAlign="Left"  Width="150px"/>
            </asp:BoundField>                         
           <asp:BoundField DataField="ProductNumber" HeaderText="Product Number">  
                 <HeaderStyle HorizontalAlign="Left" Width="150px" />
                 <ItemStyle HorizontalAlign="Left" />
            </asp:BoundField>
            <asp:BoundField DataField="Name" HeaderText="Product Name">  
                 <HeaderStyle HorizontalAlign="Left" Width="150px" />
                 <ItemStyle HorizontalAlign="Left" />
            </asp:BoundField>    
             <asp:BoundField DataField="ListPrice" HeaderText="Price">  
                 <HeaderStyle HorizontalAlign="Left" Width="50" />
                 <ItemStyle HorizontalAlign="Right" />
            </asp:BoundField>                                                               
        </Columns>
        <PagerTemplate>
          <table>
            <tr>                      
              <td><asp:LinkButton ID="FirstButton" CommandName="Page" 
    CommandArgument="First" Text="First" RunAt="server"/></td>
              <td><asp:LinkButton ID="PrevButton"  CommandName="Page" 
    CommandArgument="Prev" Text="Previous"  RunAt="server"/> </td>
              <td><asp:LinkButton ID="NextButton"  CommandName="Page" 
    CommandArgument="Next"  Text="Next"  RunAt="server"/></td>
              <td><asp:LinkButton ID="LastButton"  CommandName="Page" 
    CommandArgument="Last"  Text="Last" RunAt="server"/></td>
            </tr>
          </table>
        </PagerTemplate>
    </asp:gridview>
    <i>You are viewing page
    <%=gvProducts.PageIndex + 1%>
    of
    <%=gvProducts.PageCount%>
    </i>
    

    Source Code:

    We have our design and page handling code ready, all that is left to get some data and bind it to the grid. I am using tradional ADO.NET objects (SQLConnection, SQLCommand & SQLAdapter) objects to get all products from the tblProduct table

    protected void Page_Load(object sender, EventArgs e)
    {    
        if(!IsPostBack)
            BindData();
    }
    private void BindData()
    {
        //Bind the grid view
        gvProducts.DataSource = RetrieveProducts();
        gvProducts.DataBind();
    }
    private DataSet RetrieveProducts()
    {
        //if products is available in the viewstate, use that 
        //instead of fetching again from the database
        if (ViewState["Products"] != null)
            return (DataSet)ViewState["Products"];
        //fetch the connection string from web.config
        string connString = 
           ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
        //SQL statement to fetch entries from products
        string sql = @"Select top 10  P.ProductID, P.Name, 
            P.ProductNumber, ListPrice  from tblProduct P";
        DataSet dsProducts = new DataSet();
        //Open SQL Connection
        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();
            //Initialize command object
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                //Fill the result set
                adapter.Fill(dsProducts);
            }
        }
        return dsProducts;
    }
    

    SQL Statements:

    I have created a tblProduct table and loaded it with some test data. If you would like to use the same table, you could use below scripts.

    CREATE TABLE [dbo].[tblProduct](
     [ProductID] [int] IDENTITY(1,1) NOT NULL,
     [Name] [varchar](255) NOT NULL,
     [ProductNumber] [varchar](255) NOT NULL,
     [ListPrice] [numeric](9, 2) NOT NULL,
     CONSTRAINT [PK_tblProduct_ProductID] PRIMARY KEY CLUSTERED 
    (
     [ProductID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    DECLARE @COUNTER INT, @productname VARCHAR(255), 
     @productnumber VARCHAR(255), @listprice DECIMAL
    SET @COUNTER = 0
    SET @productname = 'product name '
    SET @productnumber = 'product number '
    SET @listprice = 500
    WHILE(@COUNTER <= 20)
    BEGIN
     SET @listprice= @listprice + 100
     INSERT INTO [dbo].[tblProduct]
         VALUES
               (@productname + convert(VARCHAR, @COUNTER)
               ,@productnumber + convert(VARCHAR, @COUNTER)
               ,@listprice)
     SET @COUNTER = @COUNTER + 1           
    END
    

    Screenshots:

    When you run the application, it would take you the default page.

    Now if you click on “Next” link, it would take you to the next page. On the next page, you would see next 5 products

    When you click on the “Last” link, it would take you to the last page.

    Now if you click on “Previous” page, it would take you to page 4.

    If you click on the “First” link it would take you to the first page.

    Be Sociable, Share!
      Post Tagged with , , ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]

    Leave a Reply