Paging and Sorting in ASP.Net GridView


The GridView is a great web control when you want to display data from the database. Out of the box it has built-in paging, sorting and a multitude of events that you can control. Recently I thought about the paging aspect of the control and thought about how you could display the page numbers as something other than numbers, such as letters. Well here's the answer! This code has not been requested by any of my customers but I thought it would be cool to try it out!

To begin with open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.

Open the Default.aspx page and add a GridView control to the page.

Here, I am going to demonstrate a sample on GridView Custom Paging. I want to display records from Product tables.

GridView Markup

<asp:GridView CellSpacing="1" ID="gvProduct" PageSize="25" Width="100%" runat="server"
                    AutoGenerateColumns="False" GridLines="None" AllowPaging="True" AllowSorting="True"
                    OnPageIndexChanging="gvProduct_PageIndexChanging" OnRowDataBound="gvProduct_RowDataBound"
                    OnSorting="gvProduct_Sorting">
                    <RowStyle BackColor="#E3EAEB" VerticalAlign="Middle" />
                    <HeaderStyle BackColor="#1C5E55" HorizontalAlign="Left" Font-Bold="True" ForeColor="White" />
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:BoundField HeaderText="Sr.No.">
                            <HeaderStyle HorizontalAlign="Center" />
                            <ItemStyle HorizontalAlign="Center" Width="10%" />
                        </asp:BoundField>
                        <asp:BoundField HeaderText="ProductID" SortExpression="ProductID" DataField="ProductID" />
                        <asp:BoundField HeaderText="ProductName" SortExpression="ProductName" DataField="ProductName" />
                        <asp:BoundField HeaderText="UnitPrice" SortExpression="UnitPrice" DataField="UnitPrice" />
                    </Columns>
                    <EmptyDataTemplate>
                        Sorry! Employee record was not found.
                    </EmptyDataTemplate>
                    <EmptyDataRowStyle HorizontalAlign="Center" Font-Size="Larger" Font-Bold="true" />
                    <PagerSettings Mode="NextPrevious" Position="TopAndBottom" NextPageText="Next" PreviousPageText="Prev"
                        FirstPageText="First" LastPageText="Last" />
                    <PagerTemplate>
                        <asp:Button ID="Button1" runat="server" Text="First" CommandName="Page" CommandArgument="First"
                            Enabled="<%# gvProduct.PageIndex > 0 %>" />
                        <asp:Button ID="Button2" runat="server" Text="Prev" CommandName="Page" CommandArgument="Prev"
                            Enabled="<%# gvProduct.PageIndex > 0 %>" />
                        <span id="Span1" runat="server">Page
                            <%= gvProduct.PageIndex + 1%>
                            of
                            <%= gvProduct.PageCount%>
                        </span>
                        <asp:Button ID="Button3" runat="server" Text="Next" CommandName="Page" CommandArgument="Next"
                            Enabled="<%# gvProduct.PageIndex + 1 < gvProduct.PageCount %>" />
                        <asp:Button ID="Button4" runat="server" Text="Last" CommandName="Page" CommandArgument="Last"
                            Enabled="<%# gvProduct.PageIndex + 1 < gvProduct.PageCount %>" />
                    </PagerTemplate>
                </asp:GridView>

Binding data

Now we need to bind custom result to our gridview, I have define a private function BindData which will take currentPage number as a input and populate result accordingly and return Total record count

private void BindData()
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        string selectSQL = "SELECT ProductID, ProductName, UnitPrice FROM Products";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();

        adapter.Fill(ds, "Products");

        try
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataView DV = ds.Tables[0].DefaultView;

                if (Session["sortBy"] != null)
                {
                    DV.Sort = Session["sortBy"].ToString();
                }
                gvProduct.DataSource = DV;
                gvProduct.DataBind();
            }
            else
            {
                gvProduct.DataSource = null;
                gvProduct.DataBind();
            }
        }
        catch (Exception oException)
        {
            // The connection failed. Display an error message.
        }
    }

Sorting Event

protected void gvProduct_Sorting(object sender, GridViewSortEventArgs e)
    {
        Session["sortBy"] = e.SortExpression;
        BindData();
    }

Paging Event

protected void gvProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvProduct.PageIndex = e.NewPageIndex;
        BindData();
    }

Page Load

On page load we need to call Bind Data functions

 protected void Page_Load(object sender, EventArgs e)
    {
        Session["sortBy"] = null;
        if (!IsPostBack)
        {
            BindData();
        }
    }

Or download attached file for GridView Custom Paging in ASP.NET 3.5.


Similar Articles