namespace WebApplication2
{
public partial class zhuyemian : System.Web.UI.Page
{
protected static PagedDataSource ps = new PagedDataSource();//创建一个分页数据源的对象且一定要声明为静态
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind(0);
}
}
public void Bind(int CurrentPage)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data source=DESKTOP-0GCALH4;User Id=sa;Pwd=199872; DataBase=demo1;trusted_connection=true;";
string cmdText = "select * from Schooltable";
SqlDataAdapter sda = new SqlDataAdapter(cmdText,con);
DataSet ds = new DataSet();
sda.Fill(ds, "Schooltable");
ps.DataSource = ds.Tables["Schooltable"].DefaultView;
ps.AllowPaging = true;//是否可以分页
ps.PageSize = 4 ;//每页显示的数量
ps.CurrentPageIndex = CurrentPage;//取得当前的页码
this.DataList1.DataSource = ps;
this.DataList1.DataKeyField = "num";
this.DataList1.DataBind();
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
switch (e.CommandName)
{
//以下几个为捕获用户点击上一页 下一页等。。时发生的事件
case "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 Mypagenum = 0;
if (!txtpage.Text.Equals(""))
Mypagenum = Convert.ToInt32(txtpage.Text.ToString());
if (Mypagenum <= 0 || Mypagenum > PageCount)
Response.Write("<script>alert('页数超出总页数')</script>");
else
Bind(Mypagenum - 1);
}
break;
}
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{ //得到脚模板中的控件,并创建变量
Label Currentpage = e.Item.FindControl("lbnowpage") as Label;
Label PageCount = e.Item.FindControl("lbcount") as Label;
LinkButton FirstPage = e.Item.FindControl("lbtnfirst") as LinkButton;
LinkButton PrePage = e.Item.FindControl("lbtnpre") as LinkButton;
LinkButton NextPage = e.Item.FindControl("lbtnnext") as LinkButton;
LinkButton LastPage = e.Item.FindControl("lbtnlast") 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;
}
}
}
}
}