在 DataList的页脚那里加上按钮
protected static PagedDataSource ps = new PagedDataSource();//调用分页
public void Bind(int CurrentPage)
{ps.DataSource = myDs.Tables["CJB"].DefaultView;
ps.AllowPaging = true; ps.PageSize = 5;//显示多少行 ps.CurrentPageIndex = CurrentPage; DataList1.DataSource = ps; DataList1.DataKeyField = "学号"; DataList1.DataBind();}
下面代码是在DataList的ItemCommand事件里打的
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{ switch (e.CommandName) { case "first":这里是按钮的名字 Label4.Text = "first"; ps.CurrentPageIndex = 0; Bind(ps.CurrentPageIndex); break; case "pre":这里是按钮的名字 ps.CurrentPageIndex = ps.CurrentPageIndex - 1; Bind(ps.CurrentPageIndex); break;case "next":这里是按钮的名字
ps.CurrentPageIndex = ps.CurrentPageIndex + 1; Bind(ps.CurrentPageIndex); break; case "last":这里是按钮的名字 ps.CurrentPageIndex = ps.PageCount - 1; Bind(ps.CurrentPageIndex); break; case "search":这里是按钮的名字 if (e.Item.ItemType == ListItemType.Footer) { int PageCount = int.Parse(ps.PageCount.ToString()); TextBox txtPage = e.Item.FindControl("txtPage") as TextBox; int MypageNu = 0; if (!txtPage.Text.Equals("")) { MypageNu = Convert.ToInt32(txtPage.Text.ToString()); } if (MypageNu <= 0 || MypageNu > PageCount) { Response.Write("<script>alert('请输入页数确定没有超过总页数!')</script>"); } else { Bind(MypageNu -1); } } break; } }下面代码是在ItemDataBound事件里的
主要功能是判断
if(DataList1里没有数据)
{
把分页按钮隐藏起来的代码
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{ if (e.Item.ItemType == ListItemType.Footer){ Label CurrentPage = e.Item.FindControl("labNowPage") as Label; Label PageCount = e.Item.FindControl("labCount") as Label; LinkButton FirstPage = e.Item.FindControl("lnkbtnFirst") as LinkButton; LinkButton PrePage = e.Item.FindControl("lnkbtnFront") as LinkButton; LinkButton NextPage = e.Item.FindControl("lnkbtnNext") as LinkButton; LinkButton LastPage = e.Item.FindControl("lnkbtnLast") as LinkButton; CurrentPage.Text = (ps.CurrentPageIndex + 1).ToString(); PageCount.Text = ps.PageCount.ToString(); if (ps.IsFirstPage) { FirstPage.Enabled = false; PrePage.Enabled = false; } if (ps.IsLastPage) { NextPage.Enabled = false; LastPage.Enabled = false; } } }这样就可以达到分页功能了