日期:2014-05-19  浏览次数:20586 次

Repeater控件能分页吗?
默认似乎不能,   可是如果不能的话要它似乎没什么用了吧,   毕竟很少有页面一次把所有的记录都读出来的,至少要分一下页,给人以好的阅读界面

那么如何用其他方式如何分页呢,   比如说要一个像百度贴吧一样的分页方式.

我的想法是,取得Dataset中Datatable中的总记录数,然后除去每页需要显示的贴子数,看看总共需要多页,   再依次把页码写出来,   然后再传递进页面一个页码参数,   利用页码搜索显示记录的位置!

但目前有个问题就是如何显示记录位置,   比如第50--100个记录   如何跟数据绑定联系到一块,默认的数据绑定是全部都显示出来.

如果不行的话,   DataGrid的分页能设置的像百度贴吧一样的分页方式吗?




------解决方案--------------------
说明:把从数据库中取到的数据赋给PagedDataSource对象的DataSource属性,然后分别设置PagedDataSource对象的AllowPaging属性(允许分页)

、PageSIze属性,CurrentPageIndex属性

1、首先在窗体拖入一个 Repeater控件,页面代码如下,红色部分为自行添加代码

<asp:Repeater id= "Repeater1 " runat= "server ">
<ItemTemplate>
<li>
<%#DataBinder.Eval(Container.DataItem, "au_fname ")%>
<%#DataBinder.Eval(Container.DataItem, "au_lname ")%>
<%#DataBinder.Eval(Container.DataItem, "phone ")%>
</li>
</ItemTemplate>
</asp:Repeater>

2、后台代码

页面载入事件代码

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
RepeaterDataBind();
}

数据绑定方法代码,自定义方法

private void RepeaterDataBind()
{ //定义数据连接对象,其中数据库连接字符串是在Web.Config文件中定义的.
SqlConnection conn=new SqlConnection(ConfigurationSettings.AppSettings[ "con "].ToString());
//创建SQL语句

string sql= "select au_fname,au_lname,phone from authors ";

//创建数据适配器对象
SqlDataAdapter da=new SqlDataAdapter(sql,conn);

//创建DataSet对象
DataSet ds=new DataSet();
try
{
da.Fill(ds, "authors ");

//创建分页类
PagedDataSource objPage=new PagedDataSource();

//设置数据源
objPage.DataSource=ds.Tables[ "authors "].DefaultView;

//允许分页
objPage.AllowPaging=true;

//设置每页显示条数
objPage.PageSize=5;

//定义变量用来保存当前页索引
int curPage;

//判断是否有页面跳转请求
if(Request.QueryString[ "Page "]!=null)
curPage=Convert.ToInt32(Request.QueryString[ "Page "]);
else
curPage=1;
objPage.CurrentPageIndex=curPage-1;
this.Label1.Text= "当前页:第 "+curPage.ToString()+ "页 ";
if(!objPage.IsFirstPage)
{ //定义 "上一页 "超级连接的URL为:当前执行页面的虚拟路径,并传递下一页面的索引植
this.HyperLink1.NavigateUrl=Request.CurrentExecutionFilePath+ "?Page= "+Convert.ToString(curPage-1);
}
if(!objPage.IsLastPage)
{
this.HyperLink2.NavigateUrl=Request.CurrentExecutionFilePath+ "?Page= "+Convert.ToString(curPage+1);
}
this.Repeater1.DataSource=objPage;
this.Repeater1.DataBind();
}
catch(Exception error)
{
Response.Write(error.ToString());
}

}