用DataReader实现分页,让我头疼了好多天。为什么我非的用DataReader控件实现分页呢?大家看看(http://www.wrclub.net/mb/)这个页面,也许有点明白了吧!对数据的横竖排列我们可以随意控制!
ASP.net中,最容易完成分页操作的是DataGrid,其次是DataList控件;但它们对数据的显示却做了限制,使得数据显示变得很难操作。DataReader模拟快速、仅向前的只读游标的操作,完成分页根本不可能,针对DataReader实现分页也只能从sql语句分析,但它对数据显示完全自由,我们可以根据自己的意愿来定义数据的显示方式!
代码如下:
<%@ Page Language="C#" Debug="true" %>
<%@OutputCache Duration="3" VaryByParam="none"%>
<%@Import Namespace="System.Data"%>
<%@Import Namespace="System.Data.SqlClient"%>
//以下源码由网人俱乐部提供,作者:福星,网址:http://www.wrclub.net/
//转摘请注明出处和作者
//定义每页显示记录数
int PageSize=9;
SqlConnection conn;
void Page_Load(Object src,EventArgs e)
{
int RecordCount,PageCount,CurrentPage,startID,endID;
//建立与数据库的连接
conn =new SqlConnection(ConfigurationSettings.AppSettings["strconn"]);
conn.Open();
//第一次请求执行
if(!Page.IsPostBack)
{
//计算总共有多少记录
RecordCount = CalculateRecord();
//计算总共有多少页
//取整
PageCount = RecordCount/PageSize;
if (RecordCount%PageSize > 0)
PageCount = PageCount + 1;
lblPageCount.Text = PageCount.ToString();
lblRecordCount.Text = RecordCount.ToString();
CurrentPage = 0;
}
//定义一个临时变量
string startIDt,endIDt;
//设置下一页开始ID
startID=0;
//设置上一页结束ID
endID=0;
startIDt=Request.Params["sid"];
endIDt=Request.Params["eid"];
//获得下一页开始ID
if(startIDt!=null)
startID=Convert.ToInt32(startIDt);
//获得上一页结束ID
if(endIDt!=null)
endID=Convert.ToInt32(endIDt);
//sql语句开始部分
string ConnStr="select top "+PageSize+" * from article where classid=1 ";
//如果有下一页开始ID的值,说明点击了“下一页”,条件语句查询的ID小于开始ID(这里排序为ID倒序)
if(startID>0)
ConnStr+=" and id<"+startID;
//如果有上一页结束ID的值,说明点击了“上一页”,条件语句查询的ID大于结束ID(这里排序为ID倒序)
if(endID>0)
ConnStr+=" and id>"+endID;
//ID倒序
ConnStr+=" order by id desc";
//DataReader执行以上sql语句
SqlCommand cmd=new SqlCommand(ConnStr,conn);
SqlDataReader myReader = cmd.ExecuteReader();
string HTML="
mblist.InnerHTML=HTML;
//获得页的值
if(Request.Params["page"]!=null)
CurrentPage = Convert.ToInt32(Request.Params["page"]);
if(PageCount==0)
{
lblCurrentPage.Text = "0";
pagelist.InnerHTML="上一页 下一页";
}
else
{
lblCurrentPage.Text = CurrentPage.ToString();
if(CurrentPage==PageCount)
pagelist.InnerHTML="上一页 下一页";
if(CurrentPage==0)
{
pagelist.InnerHTML="上一页 下一页";
lblCurrentPage.Text = (CurrentPage+1).ToString();
}
}
}
//获得记录总数
public int CalculateRecord()
{
int intCount;
string strCount = "select count(*) from article where classid=1";
SqlCommand MyComm = new SqlCommand(strCount,conn);
SqlDataReader dr = MyComm.ExecuteReader();
if(dr.Read())
{
intCount = Int32.Parse(dr[0].ToString());
}
else
{
intCount = 0;
}
dr.Close();
return intCount;
}
注明:下一页开始ID值为最接近下一页开始ID值,上一页结束ID为最接近上一页结束ID。我这个写的相对实现了数据的自定义显示,对于分页功能还不是很强大,大家可以在此基础上增加功能。



