前台:
<%@ Page language="c#" Codebehind="DataGridCustomPage.aspx.cs" AutoEventWireup="false" Inherits="CommonFunction.DataGridCustomPage" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DataGridCustomPage</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<h2>DataGrid自定义分页的例子</h2>
<asp:datagrid id="dgCustomPage" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 48px"
runat="server" Width="376px" AutoGenerateColumns="False" CellPadding="4" BackColor="White"
BorderWidth="1px" BorderStyle="None" BorderColor="#3366CC" Height="20px" AllowPaging="True"
AllowCustomPaging="True" PageSize="5">
<SelectedItemStyle Font-Bold="True" ForeColor="#CCFF99" BackColor="#009999"></SelectedItemStyle>
<ItemStyle ForeColor="#003399" BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" ForeColor="#CCCCFF" BackColor="#003399"></HeaderStyle>
<FooterStyle ForeColor="#003399" BackColor="#99CCCC"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="LastName" HeaderText="姓名"></asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="姓"></asp:BoundColumn>
<asp:BoundColumn DataField="City" HeaderText="城市"></asp:BoundColumn>
<asp:BoundColumn DataField="BirthDate" HeaderText="出生年月" DataFormatString="{0:D}"></asp:BoundColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#003399" BackColor="#99CCCC" Mode="NumericPages"></PagerStyle>
</asp:datagrid>
</form>
</body>
</HTML>
后台:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
namespace CommonFunction
...{
/**//// <summary>
/// DataGridCustomPage 的摘要说明。
/// </summary>
public class DataGridCustomPage : System.Web.UI.Page
...{
protected System.Web.UI.WebControls.DataGrid dgCustomPage;
//定义全局变量用来保存每页的起始项索引
int startIndex=0;
private void Page_Load(object sender, System.EventArgs e)
...{
//页面初试化时进行数据绑定
if(!IsPostBack)
DataGridDataBind();
}
private void DataGridDataBind()
...{
//定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
//创建数据适配器对象
SqlDataAdapter da = new SqlDataAdapter("select LastName,FirstName,BirthDate,City from Employees",conn);
//创建DataSet对象
DataSet ds = new DataSet();
try
...{
//从指定的索引开始取PageSize条记录
da.Fill(ds,startIndex,dgCustomPage.PageSize,"CurDataTable");
//填充数据集
da.Fill(ds,"AllDataTable");
//设置DataGrid控件实际要显示的项数
dgCustomPage.VirtualItemCount = ds.Tables["AllDataTable"].Rows.Count;
//进行数据绑定
dgCustomPage.DataSource = ds.Tables["CurDataTable"];
dgCustomPage.DataBind();
}
catch(Exception error)
...{
Response.Write(error.ToString());
}
}


Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
...{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
...{
this.dgCustomPage.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgCustomPage_PageIndexChanged);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void dgCustomPage_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
...{
//设置DataGrid当前页的索引值为用户选择的页的索引
dgCustomPage.CurrentPageIndex = e.NewPageIndex;
//取得当前页为止总共有多少条记录,以便在下一页就从该记录开始读取
startIndex = dgCustomPage.PageSize * dgCustomPage.CurrentPageIndex;
//重新绑定数据
DataGridDataBind();
}
}
}
int pageCount;//总页数
int currentCount;//总条数
int currentPage;//当前页
GetData GD = new GetData();
DataSet ds = new DataSet();
SqlConnection conn;
SqlCommand mycmd;
protected void Page_Load(object sender, EventArgs e)
{
GetData GD = new GetData();
//判断Cookies["admin"]["adminName"];Cookies["admin"]["adminId"]是否存在
//if (Request.Cookies["admin"] == null)
//{
// Response.Redirect("AdminLogin.aspx");
//}
////判断Cookies["admin"]是否存在
//else if (Request.Cookies["admin"]["adminName"] == null && Request.Cookies["admin"]["adminId"] == null)
//{
// Response.Redirect("AdminLogin.aspx");
//}
//else
//{
// ViewState["adminName"] = Request.Cookies["admin"]["adminName"].ToString();
// ViewState["adminId"] = Request.Cookies["admin"]["adminId"].ToString();
//}
//启动智能导航
Page.SmartNavigation = true;
if (!IsPostBack)
{
currentCount = GD.pCount();
Label1.Text = currentCount.ToString();
Label2.Text = GD.pInCount().ToString();
Label3.Text = GD.pOutCount().ToString();
Label4.Text = GD.zCount().ToString();
Label5.Text = GD.zInCount().ToString();
Label6.Text = GD.zOutCount().ToString();
if (currentCount == 0) //计算总页数
{
pageCount = 1;
}
else
{
pageCount = currentCount % GridView1.PageSize == 0 ? currentCount / GridView1.PageSize : currentCount / GridView1.PageSize + 1;
}
currentPage = 1;
ViewState["PageCount"] = pageCount;
ViewState["pageIndex"] = currentPage;
listUser();
}
}
public void listUser()
{
if (currentPage == 0)
{
currentPage = 1;
}
conn = GD.Conn();
conn.Open();
mycmd = new SqlCommand("sp_PagerUser", conn);
mycmd.CommandType = CommandType.StoredProcedure;
//每页数量
mycmd.Parameters.Add(new SqlParameter("@PageSize", SqlDbType.Int));
mycmd.Parameters["@PageSize"].Value = GridView1.PageSize;
//当前页码
mycmd.Parameters.Add(new SqlParameter("@PageIndex", SqlDbType.Int));
mycmd.Parameters["@PageIndex"].Value = currentPage;
//在这里只能用DataSet,不可以用ExecuteReader,因为他是按顺序读取,不支持分页
SqlDataAdapter sda = new SqlDataAdapter(mycmd);
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
////总页数
LblPageCount.Text = ViewState["PageCount"].ToString();
////当前页
LblCurrentIndex.Text = (Convert.ToInt32(ViewState["pageIndex"].ToString())).ToString();
////判断首页,上一页,下一页,尾页是否可用;
CheckPageCount();
}
public void Page_OnClick(Object sender, CommandEventArgs e)
{
//当前页
currentPage = (int)ViewState["pageIndex"];
//总页数
pageCount = (int)ViewState["PageCount"];
string cmd = e.CommandName;
//判断cmd,以判定翻页方向
switch (cmd)
{
case "btnnext":
if (currentPage < (pageCount)) currentPage++;
break;
case "btnprev":
//if (currentPage > 0) currentPage--;
if (currentPage > 0) currentPage--;
break;
//最后一页
case "btnlast":
//currentPage = pageCount - 1;
currentPage = pageCount;
break;
//第一页
default:
currentPage = 1;
break;
}
//当前页
ViewState["pageIndex"] = currentPage;
listUser();
}
//如果当前只有一页,则四者皆不可用,如果当前页为1,则首页不可用,如果当前页为未页,则尾页不能用.
public void CheckPageCount()
{
first.Enabled = true;
prev.Enabled = true;
next.Enabled = true;
Last.Enabled = true;
int i = Convert.ToInt32(ViewState["PageCount"].ToString());
//如果只有一页
if (i == 1)
{
first.Enabled = false;
prev.Enabled = false;
next.Enabled = false;
Last.Enabled = false;
}
else if (Convert.ToInt32(ViewState["pageIndex"].ToString()) == 1)
{
first.Enabled = false;
prev.Enabled = false;
}
if (Convert.ToInt32(ViewState["pageIndex"].ToString()) == Convert.ToInt32(ViewState["PageCount"].ToString()))
{
Last.Enabled = false;
next.Enabled = false;
}
}
本文介绍了一个使用ASP.NET DataGrid实现自定义分页的例子,包括前后端代码配置及实现方式,展示了如何通过设定每页显示的数据量及切换页码来实现数据分页功能。
1164

被折叠的 条评论
为什么被折叠?



