Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Custom Control for Effective Paging and Page Navigation for GridView with Full Source

5.00/5 (1 vote)
26 Sep 2014CPOL3 min read 18.7K   453  
Creating custom control for gridview paging and page navigation

Introduction

This is an easy and ready to integrate custom control for GridView; created with default controls available in .NET.

It can be integrated into existing GridView with minimal changes to the code. The major advantage is flexibility. Pagination can be added to the GridView either on top or at the bottom or both.

The complete demo project source code is attached here. So you can change/customize further. Please feel free to contact if you have any queries/clarifications or if any support or assistance is required.

Image 1

Background

My search across code sites forced me to develop an effective grid view custom control with paging and page navigation to develop this custom control ('GridViewPaging') and I thought of sharing through CodeProject to save your time with this approach.

Prerequisites to Run Demo

  • Microsoft SQL Server 2005/2008/2012
  • Visual Studio 2010 or higher

Demo System Setup

  1. Create a database with name GridViewDemo.
  2. Run the "Table_Create_Script.sql" Script File from the downloaded folder.
  3. Run DataScript file to insert records into database.

    Note: DataScript file: Can be used to insert records into table by specifying the number

  4. Based on your system setup, change ‘connectionstring’ in web.config

Using the Code

GridView is the commonly used control across applications, hence paging and page navigation functionality should be common for all GridViews. So it is better to create a common user control and make it reusable.

A user control has been created with name "GridViewPaging" and the common ASP.NET controls are used in the "GridViewPaging".

'GridViewPaging' custom control has three ASP controls:

  1. DropDownList
  2. Label and
  3. TextBox

DropDownList is to select number of GridView rows per page.

Label control is to display how many row(s) in current page and total records.

And finally, TextBox is to easily navigate to a particular page number.

To navigate to First, Previous, Next and Last page, simple keyboard less than (<) and greater than (>) symbols are used to avoid loading issues of images.

HTML Source Code of 'GridViewPaging'

HTML
<table class="tablePaging" border="0" width="100%">
  <tr style=" background-color:#507CD1; color:White">
    <td style="width: 15%; text-align: left;">
      <asp:Label ID="lblPageSize" runat="server" Text="Page Size: "></asp:Label>
      <asp:DropDownList ID="PageRowSize" runat="server" 
      OnSelectedIndexChanged="PageRowSize_TextChanged"
        AutoPostBack="true">
        <asp:ListItem Selected="True">10</asp:ListItem>
        <asp:ListItem>25</asp:ListItem>
        <asp:ListItem>50</asp:ListItem>
        <asp:ListItem>100</asp:ListItem>
        <asp:ListItem>500</asp:ListItem>
        <asp:ListItem>1000</asp:ListItem>
      </asp:DropDownList>
    </td>
    <td style="width: 55%; text-align: center;" class="style1">
      <asp:Label ID="RecordDisplaySummary" runat="server"></asp:Label>
    </td>
    <td style="width: 30%; text-align: right;">
      <asp:LinkButton ID="LbFirst" runat="server" ForeColor="White" 
      OnClick="First_Click" ToolTip="First Page" Style="text-decoration: none;
        font-size: large"><<</asp:LinkButton>&nbsp;
      <asp:LinkButton ID="lBPrevious" runat="server" ForeColor="White" 
      OnClick="Previous_Click" ToolTip="Previous Page" Style="text-decoration: none;
        font-size: large"><</asp:LinkButton>&nbsp;
      <asp:TextBox ID="SelectedPageNo" runat="server" 
      BorderColor="#CCCCCC" BorderStyle="Solid"
        BorderWidth="1px" Font-Names="Verdana" Font-Size="Small" 
        OnTextChanged="SelectedPageNo_TextChanged"
        Width="57px" AutoPostBack="True" ToolTip="Enter text and click enter" 
        MaxLength="7"></asp:TextBox>&nbsp; of
      <asp:Label ID="lTotalCount" runat="server" Text=""></asp:Label>
      <asp:LinkButton ID="lBNext" runat="server" ForeColor="White" 
      OnClick="Next_Click" ToolTip="Next Page" Style="text-decoration: none;
        font-size: large">></asp:LinkButton>&nbsp;
      <asp:LinkButton ID="lBLast" runat="server" ForeColor="White" 
      OnClick="Last_Click" ToolTip="Last Page" Style="text-decoration: none;
        font-size: large">>></asp:LinkButton>
    </td>
  </tr>
  <tr id="trErrorMessage" runat="server" visible="true">
    <td colspan="3" style="background-color: #e9e1e1;">
      <asp:Label ID="GridViewPagingError" runat="server" 
      Font-Names="Verdana" Font-Size="9pt"
        ForeColor="Red"></asp:Label>
      <asp:HiddenField ID="TotalRows" runat="server" Value="0" />
    </td>
  </tr>
</table>

'GridViewPaging' handles the following events for GridView:

C#
/// On click event for first page link button
protected void First_Click(object sender, EventArgs e) {} 

/// On click event for Next page link button
protected void Next_Click(object sender, EventArgs e){}

/// On click event for previous page link button 
protected void Previous_Click(object sender, EventArgs e) {}

/// On click event for Last page link button
protected void Last_Click(object sender, EventArgs e) {} 

/// Handles the TextChanged event of the PageRowSize control.
protected void PageRowSize_TextChanged(object sender, EventArgs e) {}     

/// Handles the TextChanged event of the SelectedPageNo control.
protected void SelectedPageNo_TextChanged(object sender, EventArgs e) {}

Please go through the code to find the implementation for the above events.

Integrating 'GridViewPaging' to GridView

As mentioned earlier, 'GridViewPaging' can be added to the GridView either on top or bottom or both.

Now, for this demo, it has been added on top of the GridView.

Steps to Follow to Integrate

  1. Register 'GridViewPaging' to the page where the GridView required paging/navigation. In this demo, it is in Default.aspx page.
    HTML
    <%@ Register Src="~/UserControl/GridViewPaging.ascx" 
    TagName="GridViewPager" TagPrefix="asp" %>
  2. Add GridViewPager on top of the Gridview
    HTML
    <asp:GridViewPager ID="UCGridViewPaging" runat="server" />
  3. Set properties to GridView:
    HTML
    <asp:GridView AllowPaging="True" AllowSorting="True"

    Here it is looks like:

    HTML
    <asp:Content ID="BodyContent" 
    runat="server" ContentPlaceHolderID="MainContent">
      <contenttemplate>
          <asp:GridViewPager ID="UCGridViewPaging" runat="server" />
          <asp:GridView ID="GridViewUsers" runat="server" 
          AllowPaging="True" AllowSorting="True"
            CellPadding="4" ForeColor="#333333" 
            GridLines="None" OnRowCreated="GridViewUsers_RowCreated"
            OnSorting="GridViewUsers_Sorting" Width="100%">
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" 
            ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" 
            ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" 
            HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" 
            ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
            <PagerTemplate>
            </PagerTemplate>
            <EmptyDataTemplate>
              There are currently no items in this table.
            </EmptyDataTemplate>
          </asp:GridView>
        </contenttemplate>
    </asp:Content>

    That's all at the design side.

    Now, we need to look into how to handle user control events in GridView.

    For this, we need to create an EventHandler. In the user control source code, we have created the following event handler on top of page load.

    C#
    public EventHandler pagingClickArgs;

    This needs to be handled in the GridView page by registering a function to it. So whenever event occurred, it will call the main page event to reload the data.

  4. Add the following code into GridView Page load event:
    C#
    UCGridViewPaging.pagingClickArgs += new EventHandler(Paging_Click);
  5. Add the following method:
    C#
    /// <summary>
    /// Handles the Click event of the Paging control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The 
    /// <see cref="EventArgs"/> instance containing the event data.</param>
    private void Paging_Click(object sender, EventArgs e)
    {
     GridViewUsers.PageSize = Convert.ToInt32
     (((DropDownList)UCGridViewPaging.FindControl("PageRowSize")).SelectedValue);
     GridViewUsers.PageIndex = Convert.ToInt32
     (((TextBox)UCGridViewPaging.FindControl("SelectedPageNo")).Text) - 1;
      //Reload the Grid
     PopulateData();
    }

Sorting is handled in the normal way.

Using the SQL Files

If you want to run the demo project, follow the demo setup instruction provided above.

The attached zip file contains two SQL script files. First, run the script file to create a demo table and execute the DataScript script file to insert dummy data into table.

SQL
DECLARE @RecordCount INT
DECLARE @LoopCount INT
SET @LoopCount = 0

-- For users. Please change only the following value, do not change anything else if you are not sure about it
-- Based on the record count it will create those many records in Demo_Table in the GridViewDemo database

Truncate table demo_table

WHILE(@LoopCount < @RecordCount)
BEGIN

   SET @LoopCount = @LoopCount + 1
  
  -- Declare Columns
  DECLARE @FirstName nvarchar(100)
  DECLARE @LastName nvarchar(100)
  DECLARE @Address nvarchar(100)
  DECLARE @City nvarchar(100)
  DECLARE @State nvarchar(100)
  DECLARE @Country nvarchar(100)
  
  -- Set Columns
  SET @FirstName = 'First Name ' + CONVERT(nvarchar(100), @LoopCount)
  SET @LastName = 'Last Name ' + CONVERT(nvarchar(100), @LoopCount)
  SET @Address = 'Address ' + CONVERT(nvarchar(100), @LoopCount)
  SET @City = 'City ' + CONVERT(nvarchar(100), @LoopCount)
  SET @State = 'State ' + CONVERT(nvarchar(100), @LoopCount)
  SET @Country = 'Country ' + CONVERT(nvarchar(100), @LoopCount)
  
  -- Insert into Table
  INSERT INTO Demo_Table(FirstName, LastName, Address, City, State, Country)
  SELECT @FirstName, @LastName, @Address, @City, @State, @Country
END

Points of Interest

Even though the concept of choosing the user control is old, it is powerful and flexible. With this, we can add the page navigation anywhere for the GridView.

License

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