因为项目需要,要用到DataList和Repeater的分页,但这两种加载数据的控件,本身并不自带分页功能,要控制查询语句来进行分页,但是语句过于复杂,或是条件太多,语句很难写,但用PagedDataSource进行分页,就简单多了,代码分配清晰,容易理解。
下面实例是用PagedDataSource类实现DataList控件的数据分页,也可用于Repeater。
页面后台代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
public partial class Demo : System.Web.UI.Page
{
protected SqlConnection conn; //添加数据库的操作对象
protected SqlDataAdapter da;
protected DataSet ds;
protected SqlCommand comm;
protected void Page_Load(object sender, EventArgs e)
{
getArticle();
}
private void getArticle() //取得Article数据
{
conn = new SqlConnection("server=127.0.0.1;database=ObtainEmployment;user id=sa;password=;");//取连接字符串,建立连接
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("SELECT top 50 * FROM db_Article where checkup='1' ORDER BY intime DESC ", conn);
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Article");
conn.Close();
}
catch (SqlException e1)
{
Response.Write(e1.ToString());
}
int cup = Convert.ToInt32(this.lb_CurrentPage.Text); //当前页数,初始化为地1页
PagedDataSource ps = new PagedDataSource();
ps.DataSource = ds.Tables["Article"].DefaultView;
ps.AllowPaging = true;
ps.PageSize = 6; //每页显示的数据的行数
ps.CurrentPageIndex = cup - 1;
lb_count.Text = ps.DataSourceCount.ToString(); //获取记录总数
lb_page.Text = ps.PageCount.ToString(); //获取总页数
if (!IsPostBack)
{
for (int i = 1; i < ps.PageCount + 1; i++)
{
this.DropDownList1.Items.Add(i.ToString());
}
LinkUp.Enabled = true;
LinkDown.Enabled = true;
}
try
{
DropDownList1.SelectedItem.Text = cup.ToString();
DataList1.DataSource = ps;
DataList1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
protected void LinkDown_Click(object sender, EventArgs e) //下一页按钮代码
{
try
{
lb_CurrentPage.Text = Convert.ToString(Convert.ToInt32(lb_CurrentPage.Text) + 1);
DropDownList1.SelectedValue = lb_CurrentPage.Text;
getArticle();
}
catch (Exception ex)
{
Response.Write("<script language=javascript>" + "alert(\"已经是最后一页\")" + "</script>");
lb_CurrentPage.Text = "1";
getArticle();
}
}