ReapterDemo.aspx 页面 (Repeater 设置) :
<asp:Repeater id="rptData" runat="server">
<ItemTemplate>
<font color="#ff3333">用户ID:<%# DataBinder.Eval(Container.DataItem, "CustomerID")%>
<br>
名字: <%# DataBinder.Eval(Container.DataItem, "ShipName")%>
<br>
地址: <%# DataBinder.Eval(Container.DataItem, "ShipAddress")%>
</font>
</ItemTemplate>
<AlternatingItemTemplate><font color="#3300ff">用户ID:<%# DataBinder.Eval(Container.DataItem, "CustomerID")%><br>名字: <%# DataBinder.Eval(Container.DataItem, "ShipName")%>
<br> 地址: <%# DataBinder.Eval(Container.DataItem, "ShipAddress")%> </font>
</AlternatingItemTemplate><SeparatorTemplate> </SeparatorTemplate> <FooterTemplate><br><br> <%# WriteLink()%></FooterTemplate></asp:Repeater>
代码2:ReapterDemo.aspx.cs
using AspDotNetStudy.DataAccess;
namespace AspDotNetStudy
public class ReapterDemo : System.Web.UI.Page
...{
protected System.Web.UI.WebControls.Repeater rptData;
private DBOpera dbo;
private PagedDataSource _pds;
private void Page_Load(object sender, System.EventArgs e)
...{ if(!this.IsPostBack)
...{if(Request["id"] == null) ...{ this.BindReapter(1); }
else...{ this.BindReapter(Convert.ToInt32(Request.QueryString["id"])); }
}
}
private void BindReapter(int recordPos)
...{
dbo = new DBOpera();
_pds = dbo.GetDataSource("select * from Orders", recordPos);
Response.Write("查询结果占用页数:" + _pds.PageCount);
Response.Write(" 当前页号为:" + (_pds.CurrentPageIndex + 1).ToString());
rptData.DataSource = _pds;
rptData.DataBind();
}
public string WriteLink()
...{
string s = null;
for(int i = 1;i <= _pds.PageCount;i++)
...{
s += "<a href=ReapterDemo.aspx?id=" + i.ToString() +
">" + i.ToString() + "页</a> ";
}
return s;
}
}
}
代码3:DBOpera.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
namespace AspDotNetStudy.DataAccess
...{
public class DBOpera
...{
private SqlConnection _sqlCon;
private SqlDataAdapter _sda;
private System.Web.UI.WebControls.PagedDataSource _pds;
public DBOpera()
public void CreateConnection()
...{
_sqlCon = new SqlConnection("Server=.;Database=Northwind;Uid=sa;pwd=");
_sqlCon.Open();
}
public void DisConnection()
...{
_sqlCon.Close();
_sqlCon.Dispose();
}
public PagedDataSource GetDataSource(string strSql, int recordPos)
...{
DataTable tempTable = new DataTable();
try
...{
this.CreateConnection();
_sda = new SqlDataAdapter(strSql, _sqlCon);
_sda.Fill(tempTable);
_pds = new System.Web.UI.WebControls.PagedDataSource();
_pds.DataSource = tempTable.DefaultView;
_pds.AllowPaging = true;
_pds.PageSize = 30;
_pds.CurrentPageIndex = recordPos - 1;
return _pds;
}
catch(Exception e)
...{
Console.WriteLine(e.Message);
return null;
}
finally
...{
_sda.Dispose();
_sqlCon.Dispose();
}
}
}
}
using System;
本文介绍了一个使用ASP.NET中的Repeater控件结合PagedDataSource实现分页功能的例子。该示例展示了如何从数据库中获取数据并将其显示在网页上,同时实现了翻页功能。
646





