Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

asp.net gridview paging using a dropdownlist - Part 56

Suggested Videos 
Part 53 - Default paging in gridview without using datasource controls
Part 54 - Custom paging in gridview without using datasource controls
Part 55 - Custom sorting and paging in gridview



In this video we will discuss about implementing paging in gridview and controlling the page size and page numbers using a dropdownlist, as shown in the image below.


We will be modifying the example that we discussed in Part 55. Please watch Part 55, before proceeding with this video.



Step 1: Create a table with 2 rows. The first row should contain 4 TD's, and the second row should contain 1 TD. The first row should contain the following.
1. Text - Page Size
2. DropDownList - with page sizes(5, 10, 15, 20)
3. Text - Page Number
4. DropDownList - to list the pages. The number of pages available will be computed dynamically

Since the second row contains, only one TD, set colspan=4 for this TD, so that the width of this one TD spans across 4 columns. Since, we are now going to use a dropdownlist to display the pages for navigation, we can get rid of the repeater control. Also, set the page size of gridview control to 5. At this point the HTML of WebForm1.aspx should be as shown below.
<div style="font-family: Arial">
<table>
<tr>
<td style="color: #A55129">
    <strong>Page Size:</strong>
</td>
<td>
    <asp:DropDownList ID="ddlPageSize" runat="server" 
        AutoPostBack="True" onselectedindexchanged
        ="ddlPageSize_SelectedIndexChanged">
        <asp:ListItem>5</asp:ListItem>
        <asp:ListItem>10</asp:ListItem>
        <asp:ListItem>15</asp:ListItem>
        <asp:ListItem>20</asp:ListItem>
    </asp:DropDownList>
</td>
<td style="color: #A55129">
    <strong>Page Number:
    </strong>
</td>
<td>
    <asp:DropDownList ID="ddlPageNumbers" runat="server" 
        AutoPostBack="True" onselectedindexchanged
        ="ddlPageNumbers_SelectedIndexChanged">
    </asp:DropDownList>
</td>
</tr>
<tr>
    <td colspan="4">
        <asp:GridView ID="GridView1" runat="server" 
            AllowPaging="True" PageSize="5" 
            CurrentSortField="EmployeeId"
            CurrentSortDirection="ASC" AllowSorting="True" 
            BackColor="#DEBA84" BorderColor="#DEBA84"
            BorderStyle="None" BorderWidth="1px" 
            CellPadding="3" CellSpacing="2" 
            OnSorting="GridView1_Sorting">
            <FooterStyle BackColor="#F7DFB5" 
            ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" 
                ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" 
                HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" 
                ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" 
                Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
    </td>
</tr>
</table>
</div>

Step 2: Copy and paste the following code in WebForm1.aspx.cs. Please note the following changes.
1. DatabindRepeater() method name is changed to Databind_DDLPageNumbers(). The page numbers are added to the dropdownlist(ddlPageNumbers) instead of repeater control.
2. In the Page_Load() event, we are invoking Databind_DDLPageNumbers() method and passing, ZERO as the page index and 5 as the page size.
3. Event handler method linkButton_Click() is deleted as we no longer need it.
4. In GridView1_Sorting(), notice that page size and page index is retrieved from ddlPageSize and ddlPageNumbers dropdownlist respectively. 
5. Finally notice the implementations of ddlPageSize_SelectedIndexChanged() and ddlPageNumbers_SelectedIndexChanged().
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int totalRows = 0;
                GridView1.DataSource = EmployeeDataAccessLayer.
                    GetEmployees(0, 5, 
                    GridView1.Attributes["CurrentSortField"],
                    GridView1.Attributes["CurrentSortDirection"], 
                    out totalRows);
                GridView1.DataBind();

                Databind_DDLPageNumbers(0, 5, totalRows);
            }
        }
        private void Databind_DDLPageNumbers
            (int pageIndex, int pageSize, int totalRows)
        {
            int totalPages = totalRows / pageSize;
            if ((totalRows % pageSize) != 0)
            {
                totalPages += 1;
            }

            if (totalPages > 1)
            {
                ddlPageNumbers.Enabled = true;
                ddlPageNumbers.Items.Clear();
                for (int i = 1; i <= totalPages; i++)
                {
                    ddlPageNumbers.Items.Add(new 
                        ListItem(i.ToString(), i.ToString()));
                }
            }
            else
            {
                ddlPageNumbers.SelectedIndex = 0;
                ddlPageNumbers.Enabled = false;
            }
        }

        private void SortGridview
            (GridView gridView, GridViewSortEventArgs e, 
            out SortDirection sortDirection, out string sortField)
        {
            sortField = e.SortExpression;
            sortDirection = e.SortDirection;

            if (gridView.Attributes["CurrentSortField"] != null &&
                gridView.Attributes["CurrentSortDirection"] != null)
            {
                if (sortField == gridView.Attributes["CurrentSortField"])
                {
                    if (gridView.Attributes["CurrentSortDirection"] == "ASC")
                    {
                        sortDirection = SortDirection.Descending;
                    }
                    else
                    {
                        sortDirection = SortDirection.Ascending;
                    }
                }

                gridView.Attributes["CurrentSortField"] = sortField;
                gridView.Attributes["CurrentSortDirection"] = 
                    (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
            }
        }
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection sortDirection = SortDirection.Ascending;
            string sortField = string.Empty;

            SortGridview(GridView1, e, out sortDirection, out sortField);
            string strSortDirection = 
                sortDirection == SortDirection.Ascending ? "ASC" : "DESC";

            int totalRows = 0;

            int pageSize = int.Parse(ddlPageSize.SelectedValue);
            int pageIndex = int.Parse(ddlPageNumbers.SelectedValue) - 1;
            
            GridView1.DataSource = 
                EmployeeDataAccessLayer.GetEmployees(pageIndex, pageSize, 
                e.SortExpression, strSortDirection, out totalRows);
            GridView1.DataBind();
            ddlPageNumbers.SelectedValue = (pageNumber + 1).ToString();
        }

        protected void ddlPageSize_SelectedIndexChanged
            (object sender, EventArgs e)
        {
            int totalRows = 0;

            int pageSize = int.Parse(ddlPageSize.SelectedValue);
            int pageIndex = 0;

            GridView1.PageSize = pageSize;

            GridView1.DataSource = EmployeeDataAccessLayer.
                GetEmployees(pageIndex, pageSize, 
                GridView1.Attributes["CurrentSortField"],
                GridView1.Attributes["CurrentSortDirection"], 
                out totalRows);
            GridView1.DataBind();

            Databind_DDLPageNumbers(pageIndex, pageSize, totalRows);
        }
        protected void ddlPageNumbers_SelectedIndexChanged
            (object sender, EventArgs e)
        {
            int totalRows = 0;

            int pageSize = int.Parse(ddlPageSize.SelectedValue);
            int pageIndex = int.Parse(ddlPageNumbers.SelectedValue) - 1;

            GridView1.PageSize = pageSize;

            GridView1.DataSource = EmployeeDataAccessLayer.
                GetEmployees(pageIndex, pageSize, 
                GridView1.Attributes["CurrentSortField"],
                GridView1.Attributes["CurrentSortDirection"], 
                out totalRows);
            GridView1.DataBind();
        }
    }
}

EmployeeDataAccessLayer and the stored procedure used will not change in any way.

1 comment:

  1. Hi Kudavenkat, I really appreciate your work, thank You.

    Also I found one bug in your code.
    In GridView1_Sorting event handler you have pageIndex and pageNumber that won't match each other.

    Thank You again.

    ReplyDelete

It would be great if you can help share these free resources