public static string GetPaging(int recordCount, int pageIndex, int pageSize, string pageLink, string nextPageText, string prevPageText, string homePageText, string lastPageText, string displayMsg)
{
if (pageSize < 1) { pageSize = 1; }
if (pageIndex < 1) { pageIndex = 1; }
//开始
string html = string.Empty;
string htmlLeftPage = string.Empty;
string htmlRightPage = string.Empty;
if (pageLink == string.Empty) { pageLink = "?"; }
//开始计算
long pageCount = (recordCount + pageSize - 1)/pageSize;
for (int i = 2; i >= 1; i--)
{
if (pageIndex - i >= 1)
{
htmlLeftPage += string.Format("<a class=\"pageLink\" href=\"{0}\">{1}</a>", string.Format(pageLink, (pageIndex - i)), pageIndex - i);
}
}
for (int j = 1; j <= 2; j++)
{
if (pageIndex + j <= pageCount)
{
htmlRightPage += string.Format("<a class=\"pageLink\" href=\"{0}\">{1}</a>", string.Format(pageLink, (pageIndex + j)), pageIndex + j);
}
}
long prevPage = pageIndex - 1;
if (prevPage < 1) { prevPage = 1; }
long nextPage = pageIndex + 1;
if (nextPage > pageCount) { nextPage = pageCount; }
//最后处理
if (nextPage < 1) { nextPage = 1; }
if (pageCount < 1) { pageCount = 1; }
//计算结束
string leftHtml = string.Format("<a class=\"pageLink\" {0}>{1}</a><a class=\"pageLink\" {2}>{3}</a>{4}", pageIndex != 1 ? string.Format("href=\"{0}\"", string.Format(pageLink, 1)) : "", homePageText, pageIndex != prevPage ? string.Format("href=\"{0}\"", string.Format(pageLink, prevPage)) : "", prevPageText, htmlLeftPage);
string rightHtml = string.Format("{0}<a class=\"pageLink\" {1}>{2}</a><a class=\"pageLink\" {3}>{4}</a>", htmlRightPage, pageIndex != nextPage ? string.Format("href=\"{0}\"", string.Format(pageLink, nextPage)) : "", nextPageText, pageIndex != pageCount ? string.Format("href=\"{0}\"", string.Format(pageLink, pageCount)) : "", lastPageText);
html = string.Format("<div class=\"pagerbox\">{0}<b>{1}</b>{2}</div><span>{3}</span>", leftHtml, pageIndex, rightHtml, string.Format(displayMsg, pageIndex, pageCount, recordCount));
return html;
}
为了设置样式,我在每个标签里写了class="pageLink",大家可以根据需要修改。如果不设置样式,生成的标签有点紧凑,至少应该设置一下左右的margin属性。
调用示例:
int count = GetCount();//总记录数
int pageCount = (count+pageSize-1)/pageSize;//注意这个求总页数的算法技巧
Paging = Common.WebCommon.GetPaging(count, index, pageSize, "List.html?index={0}", "下一页", "上一页", "首页", "尾页", "当前第" + index + "页,共" + pageCount + "页,共" + count + "条帖子。");
效果图: