以上是实现以后的截图,分页的链接是放在DataList 的Footer里的,看起来舒服点~不过分页的代码有很多种的~在这里还是贴一下代码,这几句是没有经过优化的,因为只是简单实现功能就可以了..但是如果需求不是很复杂,这段代码还是可以复用的。很简单的实现。没有什么技术含量。HOHO。。。
———————————————————————————————————————————————————
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind(4);
}
}
public void bind(int a)//这里方法带了一个参数,用来设置每页显示几条数据,其实无所谓!
{
string cn = ConfigurationManager.ConnectionStrings["GuestCS"].ConnectionString;//从webconfig中取出连接字符串
SqlConnection sqlcn = new SqlConnection(cn);//定义一个连接
sqlcn.Open();//打开
SqlDataAdapter sqlda = new SqlDataAdapter("select * from tb_Msg",sqlcn);//定义一个适配器
DataSet ds1=new DataSet();//定义dataset数据集
sqlda.Fill(ds1);//用适配器定义数据集
PagedDataSource pds = new PagedDataSource();//定义一个分页数据源
pds.DataSource = ds1.Tables[0].DefaultView;//把数据集中的表放进分页数据源中
pds.AllowPaging = true;//设置允许分页
pds.PageSize = a;//设置每页数据条目
ViewState["Pages"] = pds.PageCount;//用viewState["Pages"]来 存放可以分的页数
if (Request.QueryString["Page"] != null)
{
pds.CurrentPageIndex = Convert.ToInt32((Request.QueryString["Page"]))-1;
//设置当前页的索引,默认是第一页;其余的页码通过request.querystring来获取一个页码。
}
else
{
pds.CurrentPageIndex = 0;
}
ViewState["currentindex"] = Convert.ToInt32(pds.CurrentPageIndex)+1;//这里相当于一个全局变量,以便于在datalist1_itemdatabound事件中得到当前索引的数值。
DataList1.DataSource = pds;
DataList1.DataBind();//绑定:)
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
((HyperLink)e.Item.FindControl("lnk1")).NavigateUrl="?page="+1;//发出一个page变量=1,实现首页功能。
((HyperLink)e.Item.FindControl("lnk4")).NavigateUrl = "?page=" + Convert.ToInt32(ViewState["Pages"]);//末页的实现
((HyperLink)e.Item.FindControl("lnk2")).NavigateUrl = "?page=" + (Convert.ToInt32(ViewState["currentindex"])-1);//前翻页
((HyperLink)e.Item.FindControl("lnk3")).NavigateUrl = "?page=" + (Convert.ToInt32(ViewState["currentindex"]) + 1);//后翻页
((Label)e.Item.FindControl("Label5")).Text = ViewState["currentindex"].ToString()+"/"+ViewState["Pages"].ToString();//显示label
if (Convert.ToInt32(ViewState["currentindex"]) == 1)
{
((HyperLink)e.Item.FindControl("lnk2")).Enabled = false;
((HyperLink)e.Item.FindControl("lnk1")).Enabled = false;
}
if (Convert.ToInt32(ViewState["currentindex"]) == Convert.ToInt32(ViewState["Pages"]))
{
((HyperLink)e.Item.FindControl("lnk4")).Enabled = false;
((HyperLink)e.Item.FindControl("lnk3")).Enabled = false;
}
}
}
}