分页效果:
1.建立一个用户控件
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControlPage.ascx.cs" Inherits="plSystem.member.UserControlPage" %>
<script src="../Scripts/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(".inputfy").click(function () {
var strurl = window.location.href;
var kg1 = strurl.indexOf("=");
var url = strurl.substring(0, kg1 + 1);
var myString = $(".pagination").html();
var kg1 = myString.indexOf("共计");
var kg2 = myString.indexOf("页/");
var num = myString.substring(kg1+2, kg2);
var kk = $("#pagenum").val();
if (kk > parseInt(num) || kk < 0) {
alert("请输入正确的跳转数!");
return false;
}
else {
window.location.href = url + $("#pagenum").val();
}
})
})
</script>
<style type="text/css">
.pagination{
overflow:hidden; margin:0; vertical-align:middle; height:20px; line-height:20px; _zoom:1; }
.pagination *{ display:inline; float:left; margin:0; padding:0; font-size:14px; color:#616161;}
.currentPage b{ float:none; color:#f00;}
.pagination li{ list-style:none; }
.pagination li li{ position:relative; font-family: Arial, Helvetica, sans-serif }
.pagination li li a{ margin:0; padding:0 4px; color:#616161; text-decoration:none; }
.pagination li.firstPage{ margin:0 auto; border-left:3px solid #06f; }
.pagination li li.currentState a{ color:Red;font-size:13px; }
.pagination li li.currentState1 a{ font-size:13px; }
.pageinputfy{ height:18px; margin-left:3px; font-size:12px; border:0px; padding:0 2px 0 2px; background:#EAEAEA;cursor:pointer;}
.colorno{ color:#AEADA8;margin:0; padding:0 4px; }
</style>
<div class="pagination">
<ul>
<li>
<%=paginationStr%>
</li>
</ul>
</div>
2.用户控件后台代码
//分页字符
public StringBuilder paginationStr = new StringBuilder();
//总分页数 20
public int data_count;
private string page_Count;
public string Page_Count
{
set {
int count =Convert.ToInt32(Request.Cookies["myPageSize"].Value);
if (count == 0)
{
count = 17;
}
Regex re = new Regex(@"^[1-9]\d*$");
if (re.IsMatch(value))
{
data_count = Convert.ToInt32(value);
if (data_count % count != 0)
{
page_Count = string.Format("{0}", data_count / count + 1);
}
else
{
page_Count = string.Format("{0}", data_count / count);
}
}
}
}
//显示分页文字是中文 还是英文
private string text_Type;
public string Text_Type
{
set
{
if (string.IsNullOrEmpty(string.Format("{0}", value)))
{
value = "CN";
}
text_Type = value.ToUpper().Trim();
}
}
//当前页的索引
public int pageIndex = 0;
//当前请求URL
public string url = string.Empty;
//原始URL
public string baseUrl = string.Empty;
//获取所有参数集合
public Hashtable urlParameters = new Hashtable();
// 分页模式:
public void Get_URL()
{
try {
string urlParams = string.Empty;
url = Request.Url.AbsoluteUri;
baseUrl = url.Split('?').Length > 1 ? url.Substring(0, url.IndexOf('?')) : url;
urlParams = url.Split('?').Length > 1 ? url.Substring(url.IndexOf('?') + 1) : "";
if (url.Split('?').Length > 0 && url.Split('?').Length < 3)
{
if (urlParams.Trim() != "")
{
if (urlParams.Split('&').Length > 0)
{
for (int i = 0; i < urlParams.Split('&').Length; i++)
{
urlParameters.Add(urlParams.Split('&')[i].Split('=')[0], urlParams.Split('&')[i].Split('=')[1]);
}
}
}
else
{
urlParameters.Add("page", 1);
}
}
SetPaginationNumber(Convert.ToInt32(urlParameters["page"]));
}
catch
{
Page.ClientScript.RegisterStartupScript(GetType(), Guid.NewGuid().ToString(), "alert('参数错误!');top.location.href='../404.aspx'", true); Response.End();
//throw;
}
}
public void SetPaginationNumber(int PageIndexNumber)
{
int page_Count_i = Convert.ToInt32(page_Count);
string parmsStr = string.Empty;
foreach (var item in urlParameters.Keys)
{
if (item.ToString() != "page")
{
parmsStr += "&" + item.ToString() + "=" + urlParameters[item].ToString();
}
}
paginationStr.Append("<ul id=\"pagination-flickr\">");
//首页
paginationStr.Append(PageIndexNumber != 1 ? string.Format("<li class=\"next\"><a href=\"{0}?page={1}{2}\">{3}</a></li>", baseUrl, 1, parmsStr, text_Type == "EN" ? "home" : "首页") : string.Format("<li class=\"colorno\">{0}</li>", text_Type == "home" ? " last" : "首页"));
//上一页
if (PageIndexNumber < 2)
{
PageIndexNumber = 1;
paginationStr.Append(string.Format("<li class=\"colorno\">{0}</li>", text_Type == "EN" ? "prev" : "上一页"));
}
else
{
paginationStr.Append(string.Format("<li class=\"next\"><a href=\"{0}?page={1}{2}\">{3}</a></li>", baseUrl, PageIndexNumber == 1 ? 1 : PageIndexNumber - 1, parmsStr, text_Type == "EN" ? "prev" : "上一页"));
}
// 数字导航
if (page_Count_i <= 10)
{
Set_NumStr(1, page_Count_i, PageIndexNumber, parmsStr);
}
else
{
if (PageIndexNumber < 5)
{
Set_NumStr(1, 8, PageIndexNumber, parmsStr);
}
else if ((PageIndexNumber + 4) > page_Count_i)
{
Set_NumStr((page_Count_i - 6), page_Count_i + 1, PageIndexNumber, parmsStr);
}
else
{
Set_NumStr(PageIndexNumber - 3, PageIndexNumber + 4, PageIndexNumber, parmsStr);
}
}
//下一页
string kk;
if (PageIndexNumber >= page_Count_i)
{
PageIndexNumber = page_Count_i - 1;
paginationStr.Append(string.Format("<li class=\"colorno\">{0}</li>", text_Type == "EN" ? "next" : "下一页"));
paginationStr.Append(string.Format("<li class=\"colorno\">{0}</li>", text_Type == "EN" ? " last" : "尾页"));
kk = PageIndexNumber + 1 >= page_Count_i ? (PageIndexNumber + 1).ToString() : PageIndexNumber.ToString();
}
else
{
paginationStr.Append(string.Format("<li class=\"next\"><a href=\"{0}?page={1}{2}\">{3}</a></li>", baseUrl, PageIndexNumber + 1, parmsStr, text_Type == "EN" ? "next" : "下一页"));
paginationStr.Append(string.Format("<li class=\"next\"><a href=\"{0}?page={1}{2}\">{3}</a></li>", baseUrl, page_Count_i, parmsStr, text_Type == "EN" ? " last" : "尾页"));
kk = PageIndexNumber >= page_Count_i ? (PageIndexNumber + 1).ToString() : PageIndexNumber.ToString();
}
//跳转
paginationStr.Append(string.Format("<li style=\"margin-left:5px;margin-right:5px;\"><input type=\"text\" value=\"" + kk + "\" id=\"pagenum\" runat=\"server\" style=\"width:30px; height:16px; border:1px solid #899BA9;\" /> <div class=\"pageinputfy\">GO</div></li>"));
paginationStr.Append(string.Format("<li class=\"next\">共计{0}页/{1}条信息</li>", page_Count_i, data_count));
paginationStr.Append("</ul>");
}
//设置数字分页字符串1
private void Set_NumStr(int BeginNumber, int EndNumber, int PageIndexNumber, string parmsStr)
{
for (int i = BeginNumber; i < EndNumber; i++)
{
paginationStr.Append(string.Format("<li {0}><a href=\"{1}?page={2}{3}\">{4}</a></li>", i == PageIndexNumber ? "class=\"currentState\"" : "class=\"currentState1\"", baseUrl, i, parmsStr, i));
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
3. 调用方法
建立一个aspx 页面,将上面的用户控件拖放到页面目标位置
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="a.aspx.cs" Inherits="plSystem.a" %>
<%@ Register Src="member/UserControlPage.ascx" TagName="userpage" TagPrefix="page" %>
<!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></title>
<link href="Styles/index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="1">
<asp:Repeater ID="replist" runat="server">
<ItemTemplate>
<tr><td><%#Eval("id") %></td><td><%#Eval("title")%></td><td><%#Eval("tid")%></td><td><%#Eval("sendtime")%></td></tr>
</ItemTemplate>
</asp:Repeater>
</table>
<br />
<page:userpage ID="listpage" runat="server"></page:userpage>
</div>
</form>
</body>
</html>
4.后台代码
public int page_index = 1;
DB db = new DB();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
page_index = Convert.ToInt32(Request.QueryString["page"]);
if (page_index == 0)
{
page_index = 1;
}
}
catch (Exception)
{
page_index = 1;
}
}
table_bind2();
}
protected void table_bind2()
{
//每页显示像素
int myPageSize = 20;
doCook("myPageSize", myPageSize.ToString());
//当前显示页的索引
int myPageIndex = page_index;
string sql = "select id,tid,title,body,litpic,color,hot,tj,b,author,description,sendtime from t_arc where tid='16' and del='0' order by hot desc, tj desc,sort desc";
string sql_count = "SELECT COUNT(1) FROM t_arc where tid='16' and del='0'";
DataSet ds = db.getDataSetPage(sql, myPageSize, myPageIndex);
int rowCount = ds.Tables[0].Rows.Count;
if (rowCount > 0)
{
listpage.Page_Count = db.GetSingle(sql_count).ToString();
listpage.Text_Type = "CN";
listpage.Get_URL();
try
{
replist.DataSource = ds.Tables[0].DefaultView;
replist.DataBind();
}
catch (Exception)
{
replist.DataSource = ds.Tables[0].DefaultView;
replist.DataBind();
}
}
}
//获取cook HttpUtility.UrlEncode写入
public void doCook(string var, string key)
{
key = HttpUtility.UrlEncode(key);
try
{
HttpContext.Current.Response.Cookies.Add(new HttpCookie(var, key));
}
catch
{
throw;
}
}
5.分页数据方法
#region 分页方法
/// <summary>
/// 分页方法
/// </summary>
/// <param name="sql">纯sql语句</param>
/// <param name="pageSize">页面大小</param>
/// <param name="pageIndex">当前页</param>
/// <returns></returns>
public DataSet getDataSetPage(string sql, int pageSize, int pageIndex)//根据SQL语句获取数据集
{
int starindex = (pageIndex - 1) * pageSize;
int maxRecord = pageSize;
DataSet ds = new DataSet();
try
{
SqlDataAdapter oda = new SqlDataAdapter(sql, myConnection);
oda.Fill(ds, starindex, maxRecord, "t_arc");
int count = ds.Tables[0].Rows.Count;
}
catch (Exception ex)
{
throw ex;
}
return ds;
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public object GetSingle(string SQLString)
{
SqlCommand cmd = new SqlCommand(SQLString, myConnection);
try
{
myConnection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
myConnection.Close();
throw e;
}
}
#endregion