Asp.net 自定义分页功能
1、新建一个MyPage类
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for Page
/// </summary>
public class MyPage
{
public MyPage()
{
//
// TODO: Add constructor logic here
//
}
/// </summary>
/// <param name="total">总记录数</param>
/// <param name="per">每页记录数</param>
/// <param name="page">当前页数</param>
/// <param name="query_string">Url参数</param>
/// <param name="ID">参数</param>
/// <param name="currentpage">当前页</param>
/// <param name="PageSize">每页分页大小</param>
public static string pagination(int total, int per, int page, string query_string, int ID, int currentpage, int PageSize)
{
int allpage = 0;
int next = 0;
int pre = 0;
int startcount = 0;
int endcount = 0;
string pagestr = "";
if (page < 1) { page = 1; }
//计算总页数
if (per != 0)
{
allpage = (total / per);
allpage = ((total % per) != 0 ? allpage + 1 : allpage);
allpage = (allpage == 0 ? 1 : allpage);
}
next = page + 1;
pre = page - 1;
startcount = (page + 5) > allpage ? allpage - 9 : page - 4;//中间页起始序号
//中间页终止序号
endcount = page < 5 ? 10 : page + 5;
if (startcount < 1) { startcount = 1; } //为了避免输出的时候产生负数,设置如果小于1就从序号1开始
if (allpage < endcount) { endcount = allpage; }//页码+5的可能性就会产生最终输出序号大于总页码,那么就要将其控制在页码数之内
pagestr = "共<font color=\"#ff000\">" + allpage + "</font>页 共有<font color=\"#ff0000\">" + total + "</font>条记录 当前页<font color=\"#ff0000\">" + currentpage + "</font>/" + allpage + " 每页<font color=\"ff0000\">" + PageSize + "</font>条 ";
pagestr += page > 1 ? "<a href=\"" + query_string + "&page=1\">首 页</a> <a href=\"" + query_string + "&page=" + pre + "\">上一页</a>" : "首 页 上一页";
//中间页处理,这个增加时间复杂度,减小空间复杂度
for (int i = startcount; i <= endcount; i++)
{
pagestr += page == i ? " <font color=\"#ff0000\">" + i + "</font>" : " <a href=\"" + query_string + "&page=" + i + "\">" + i + "</a>";
}
pagestr += page != allpage ? " <a href=\"" + query_string + "&page=" + next + "\">下一页</a> <a href=\"" + query_string + "&page=" + allpage + "\">尾 页</a>" : " 下一页 尾 页";
return pagestr;
}
}
2、建一个TestPageDB.aspx页面;
页面代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPageDB.aspx.cs" Inherits="Report_TestPageDB" %>
<!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>Untitled Page</title>
<style type="text/css">
body{font-size: 12px;}
a {font-size: 12px; text-decoration: none; color: #2F3586;}
a:hover {background: #dedede; color: ff0000; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<%--HTML代码主体部分--%>
<TABLE cellSpacing=0 cellPadding=0 width=1004 align=center border=0>
<TBODY>
<TR>
<TD vAlign=top width=107></TD>
<TD width=26 vAlign=top background="image/line1.jpg" style="background-repeat: repeat;"> </TD>
<TD vAlign=top>
<table width="99%">
<tr>
<td colspan="3" align="center"><%--数据绑定--%>
<asp:DataList ID="detail" runat="server" Width="99%">
<HeaderTemplate><TABLE cellSpacing=0 cellPadding=0 width="100%" border=0><TBODY></HeaderTemplate>
<ItemTemplate><tr>
<td width=12 height=8><IMG height="5" src="image/main_but_09_1.gif" width="6"><%#Eval("ID") %></td>
<td><A href="news_type.aspx?ID=<%#Eval("ID") %>"><%#Eval("username") %></A> <font color="666666"><%#Eval("loginname")%></font></TD>
</tr>
<tr>
<td colspan="2" background="image/skim.gif" height="1"></td>
</tr></ItemTemplate>
<FooterTemplate></TBODY></TABLE></FooterTemplate>
</asp:DataList><%--数据绑定--%>
</td>
</tr>
<tr>
<td colspan="3" style="width: 715px" align="right"><div align="center">
<%--分页代码--%><asp:Label ID="pagelist" runat="server"></asp:Label><%--分页代码--%></td>
</tr>
</table>
</TD></TR></TBODY></TABLE>
</div>
</form>
</body>
</html>
后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Report_TestPageDB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String sql = "select * from userinfo";
int totalcount;//总记录数
int currentpage;//当前页
int PageSize = 4;//分页大小
int totalpage;//记录总页数
///总记录数
totalcount = getTotalcount("select count(id) from userinfo");
//当前页
//计算总页数;totalpage
if (totalcount / PageSize == 0)
{
totalpage = totalcount / PageSize;
}
else
{
totalpage = totalcount / PageSize + 1;
}
if (Request.QueryString["page"] == null)///指地址栏中没有PAGE字符
{
currentpage = 1;
}
if (Request.QueryString["page"] != null)
{
// 判断是否为数值
if (querystring.isNumber(Request.QueryString["page"]) == false)
{
currentpage = 1;
}
else///是数值
{
if (Request.QueryString["page"].Length > 10 || Request.QueryString["page"].Length < 1)///防止Convert.ToInt32抛出异常或者防止地址栏所得到的page=这样的值
{
currentpage = 1;
//Response.End();
}
else
{
if (Convert.ToInt32(Request.QueryString["page"]) > totalpage)///是否大于总页数
{
currentpage = totalpage;
}
else
{
if (Convert.ToInt32(Request.QueryString["page"]) <= 1)///是否小于页数1
{
currentpage = 1;
}
else
{
currentpage = Convert.ToInt32(Request.QueryString["page"]);
}
}
}
}
}
else
{
currentpage = 1;
}
detail.DataSource = myDataBind(sql, currentpage, PageSize,"userinfo");//填充数据
detail.DataBind();
pagelist.Text = MyPage.pagination(totalcount, PageSize, currentpage, "TestPageDB.aspx?id=0", 0, currentpage, PageSize).ToString();//分页/
}
/// <summary>
/// 查找结果集
/// </summary>
/// <param name="sqls">sql查询语句</param>
/// <param name="currentpage">当前页</param>
/// <param name="pagesize">每页大小</param>
/// <param name="table">数据库表名</param>
/// <returns>DataView</returns>
public DataView myDataBind(string sqls, int currentpage, int pagesize, string table)
{
int startcount;
if (currentpage < 1)
{
startcount = currentpage * pagesize;
}
else
{
startcount = (currentpage - 1) * pagesize;
}
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=testDB;Persist Security Info=True;User ID=sa;password=sa");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqls, conn);
DataSet ds = new DataSet();
da.Fill(ds, startcount, pagesize, table.ToString());
conn.Close();
return ds.Tables[0].DefaultView;
}
/// <summary>
/// 获得总记录数
/// </summary>
/// <param name="sql">sql查询语句</param>
/// <returns>int 总记录数</returns>
public int getTotalcount(String sql)
{
int i = 0;
SqlConnection conn = null;
try
{
conn = new SqlConnection("Data Source=.;Initial Catalog=testDB;Persist Security Info=True;User ID=sa;password=sa");
conn.Open();
SqlCommand cmd = new SqlCommand(sql,conn);
i = Convert.ToInt32(cmd.ExecuteScalar());
}
catch (Exception)
{
throw;
}
conn.Close();
return i;
}
}
3、建一个测试数据库testDB
建一张userinfo表,字段为id、 username 和loginname即可,插入一些测试数据。
Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
https://worktile.com