当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

DataList控件的分页

  不同于Gridview控件,Datalist控件没有自动分页支持。要支持分页功能,你必须添加代码,如下例所示:

  int PageSize, RecordCount, PageCount, CurrentPage;

  SqlConnection MyConn;

  public int IndexOfPage

  {

  get { return (int)ViewState["_IndexOfPage"]; }

  set { ViewState["_IndexOfPage "] = value; }

  }

  public int CountOfPage

  {

  get { return (int)ViewState["_CountOfPage"]; }

  set { ViewState["_CountOfPage"] = value; }

  }

  public void Page_Load(Object src, EventArgs e)

  {

  PageSize = 3;

  string MyConnString =

  @"Server=(local)\SQLEXPRESS;Integrated Security=SSPI;Database=test;Persist Security Info=True";

  MyConn = new SqlConnection(MyConnString);

  MyConn.Open();

  if (!Page.IsPostBack)

  {

  ListBind();

  CurrentPage = 0;

  IndexOfPage = 0;

  RecordCount = CalculateRecord();

  lblRecordCount.Text = RecordCount.ToString();

  PageCount = RecordCount / PageSize;

  lblPageCount.Text = PageCount.ToString();

  CountOfPage = PageCount;

  }

  }

  public int CalculateRecord()

  {

  int intCount;

  string strCount = "select count(*) as co from student";

  SqlCommand MyComm = new SqlCommand(strCount, MyConn);

  SqlDataReader dr = MyComm.ExecuteReader();

  if (dr.Read())

  {

  intCount = Int32.Parse(dr["co"].ToString());

  }

  else

  {

  intCount = 0;

  }

  dr.Close();

  return intCount;

  }

  ICollection CreateSource()

  {

  int StartIndex;

  StartIndex = CurrentPage * PageSize;

  string strSel = "select * from student";

  DataSet ds = new DataSet();

  SqlDataAdapter MyAdapter = new SqlDataAdapter(strSel, MyConn);

  MyAdapter.Fill(ds, StartIndex, PageSize, "Score");

  return ds.Tables["Score"].DefaultView;

  }

  public void ListBind()

  {

  DataList1.DataSource = CreateSource();

  DataList1.DataBind();

  lbnNextPage.Enabled = true;

  lbnPrevPage.Enabled = true;

  if (CurrentPage == (PageCount - 1)) lbnNextPage.Enabled = false;

  if (CurrentPage == 0) lbnPrevPage.Enabled = false;

  lblCurrentPage.Text = (CurrentPage + 1).ToString();

  }

  public void Page_OnClick(Object sender, CommandEventArgs e)

  {

  CurrentPage = (int)IndexOfPage;

  PageCount = (int)CountOfPage;

  string cmd = e.CommandName;

  switch (cmd)

  {

  case "next":

  if (CurrentPage < (PageCount - 1)) CurrentPage++;

  break;

  case "prev":

  if (CurrentPage > 0) CurrentPage--;

  break;

  }

  IndexPage = CurrentPage;

  ListBind();

  }

相关内容
赞助商链接