GridView Control with Pager Templete

Reference Book: ASP.NET 2.0 웹 프로젝트와 실전 프로그래밍

Creat an ASP.NET website. Under the website, create a folder named "Pager". Under the folde, create a webform named "Pager".

Create a connectionstring in web.confic named "NorthwindConnectionString".

Database is "Northwind". Used table is "Products".

Result:

Pager.aspx

========

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Pager.aspx.cs" Inherits="Pager_Pager" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Pager Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="AliceBlue"
            DataSourceID="SqlDataSource1" PageSize="4" AllowPaging="true" AlternatingRowStyle-BackColor="AliceBlue"
            ondatabound="GridView1_DataBound">
            <Columns>
                <asp:BoundField DataField="ProductName" HeaderText="ProductName"
                    SortExpression="ProductName" />
                <asp:TemplateField HeaderText="UnitPrice">
                    <ItemTemplate>
                        <asp:Label ID="lblUnitPrice" runat="server"><%#DataBinder.Eval(Container.DataItem,"UnitPrice","${0:F2}") %></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <%--<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
                    SortExpression="UnitPrice" />--%>
            </Columns>
            <PagerSettings PageButtonCount="4" />
            <PagerTemplate>
                <table>
                    <tr>
                        <td>
                            <asp:Button ID="btnPrevList" runat="server" CommandName="Page" CausesValidation="false" Text="..." />&nbsp;
                            <asp:Button ID="btnFirst" runat="server" CommandName="Page" CommandArgument="First" CausesValidation="false" Text="1" />
                            <asp:Literal ID="lFirst" runat="server" Text="..."></asp:Literal>
                           
                            <asp:Button ID="btnNum1" runat="server" CommandName="Page" CausesValidation="false" />
                            <asp:Button ID="btnNum2" runat="server" CommandName="Page" CausesValidation="false" />
                            <asp:Button ID="btnNum3" runat="server" CommandName="Page" CausesValidation="false" />
                            <asp:Button ID="btnNum4" runat="server" CommandName="Page" CausesValidation="false" />
                            <asp:Button ID="btnNum5" runat="server" CommandName="Page" CausesValidation="false" />
                           
                            <asp:Literal ID="lLast" runat="server" Text="..."></asp:Literal>                         
                            <asp:Button ID="btnLast" runat="server" CommandName="Page" CommandArgument="Last" CausesValidation="false" />&nbsp;
                            <asp:Button ID="btnNextList" runat="server" CommandName="Page" CausesValidation="false" Text="..." />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            총<asp:Label ID="TotalPagesLabel" runat="server" Font-Bold="true"></asp:Label>페이지중
                            <asp:Label ID="PageNumberLabel" runat="server" Font-Bold="true"></asp:Label>페이지
                        </td>
                    </tr>
                </table>
            </PagerTemplate>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [ProductName], [UnitPrice] FROM [Products]">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

============================================================================================

Pager.aspx.cs

==========

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Pager_Pager : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        GridView gv = (GridView)sender;
        GridViewRow pagerRow = gv.BottomPagerRow;

        Label pageNum = (Label)pagerRow.Cells[0].FindControl("PageNumberLabel");
        Label totalNum = (Label)pagerRow.Cells[0].FindControl("TotalPagesLabel");

        if ((pageNum != null) && (totalNum != null))
        {
            int page = gv.PageIndex + 1;
            int count = gv.PageCount;

            pageNum.Text = page.ToString();
            totalNum.Text = count.ToString();
        }

        CreateNumericPager(gv, pagerRow);
    }

    void CreateNumericPager(GridView gv, GridViewRow PagerRow)
    {
        //모든 컨트롤의 Visible 속성에 false를 설정하는 코드이다. 일단 모든 컨트롤들을 감춘후 코드에서 필요한 컨트롤만 다시 활성화 한다.
        Control btn;
        for (int i = 1; i <= 5; i++)
        {
            btn = PagerRow.Cells[0].FindControl("btnNum" + i);
            btn.Visible = false;
        }

        Button btnPrevList = (Button)PagerRow.Cells[0].FindControl("btnPrevList");
        btnPrevList.Visible = false;

        Button btnFirst = (Button)PagerRow.Cells[0].FindControl("btnFirst");
        btnFirst.Visible = false;

        Literal lFirst = (Literal)PagerRow.Cells[0].FindControl("lFirst");
        lFirst.Visible = false;

        Literal lLast = (Literal)PagerRow.Cells[0].FindControl("lLast");
        lLast.Visible = false;

        Button btnLast = (Button)PagerRow.Cells[0].FindControl("btnLast");
        btnLast.Visible = false;

        Button btnNextList = (Button)PagerRow.Cells[0].FindControl("btnNextList");
        btnNextList.Visible = false;

        //현재 페이지와 총 페이지를 기준으로 페이지 이동 버튼의 CommandArgument에 설정할 변수들을 준비하는 코드.
        int pageCount = gv.PageCount;
        int pageIndex = gv.PageIndex + 1;
        int pageButtonCount = gv.PagerSettings.PageButtonCount;
        int lastPage = pageButtonCount;
        if (pageCount < lastPage)
            lastPage = pageCount;

        int first = 1;
        int last = lastPage;
        if (pageIndex > last)
        {
            first = gv.PageIndex / pageButtonCount * pageButtonCount + 1;
            last = first + pageButtonCount - 1;

            if (last > pageCount)
                last = pageCount;

            if (last - first + 1 < pageButtonCount)
                first = Math.Max(1, last - pageButtonCount + 1);
        }

        //First 버튼과 <이전4페이지> 버튼이 출력될 필요가 있다면 버튼의 Visible 속성에 true를 설정하고 <이전4페이지> 버튼의 CommandArgument
        //속성에 이동할 페이지 번호를 설정한다.
        if (first != 1)
        {
            btnPrevList.Visible = true;

            int t = first - 1;
            btnPrevList.CommandArgument = t.ToString();
            btnPrevList.Text = "이전" + pageButtonCount + "페이지";

            btnFirst.Visible = true;
            lFirst.Visible = true;
        }

        //출력되여야 할 페이지 번호 버튼들의 Visible 속성에 true 를 설정하고 CommandArgument 속성에 이동할 페이지 번호를 설정한다.
        //그리고 현재 선택된 페이지는 Enabled에 false를 설정해서 클릭할수 없게 만든다.
        int count = 1;
        for (int i = first; i <= last; i++, count++)
        {
            string str = i.ToString();
            Button numButton = (Button)PagerRow.Cells[0].FindControl("btnNum" + count);
            numButton.Visible = true;
            if (i == pageIndex)
            {
                numButton.Text = str;
                numButton.Enabled = false;
            }
            else
            {
                numButton.Text = str;
                numButton.CommandArgument = str;
            }
        }

        //Last 버튼과 <다음4페이지> 버튼이 출력될 필요가 있다면 버튼의 Visible속성에 true를 설정하고, <다음4페이지> 버튼의 CommandArgument 속성에
        //이동할 페이지 번호를 설정한다.
        if (pageCount > last)
        {
            btnNextList.Visible = true;

            int t = last + 1;
            btnNextList.CommandArgument = t.ToString();
            btnNextList.Text = "다음" + pageButtonCount + "페이지";

            btnLast.Visible = true;
            lLast.Visible = true;

            btnLast.Text = pageCount.ToString();
        }
    }
}

posted @ 2009-01-08 22:36  OOK  阅读(444)  评论(0编辑  收藏  举报