Slash

习惯在追逐的过程中不断去完善自己;当你不再去追逐,你自我完善的脚步也就停滞下来了。

导航

自定义分页(适用于DataList,Repeater)

      用到的是PagedDataSource类,熟悉其中的属性和方法便能快捷掌握分页技巧,用到控件有显示当前页码的Label,上一页,下一页,首页,末页和一动态绑定页码的DropDownList,具体代码如下:

 //分页绑定方法
  void BindDataByPage()
  {
   //标记当前页码
   int currentPage=Convert.ToInt32(PageNum.Text);
   
   //新建数据库操作类
   EasybuyExcuData goodCategory=new EasybuyExcuData();
   int categoryID=Int32.Parse(Request.Params["CategoryID"]);
   

   DataSet ds=new DataSet();

   //获得返回的dataset对象,按类别编号
   ds=goodCategory.GetGoodsCategory(categoryID);

   //新建分页对象实例
   PagedDataSource pds=new PagedDataSource();

   pds.DataSource=ds.Tables[0].DefaultView;

   pds.AllowPaging=true;
   pds.PageSize=4;

   //由于页码索引从零开始,则执行减一操作
   pds.CurrentPageIndex=currentPage -1;

   btnFirst.Enabled=true;
   btnFront.Enabled=true;
   btnNext.Enabled=true;
   btnLast.Enabled=true;

   if(currentPage==1)
   {
    btnFront.Enabled=false;
    btnFirst.Enabled=false;
   }

   if(currentPage==pds.PageCount)
   {
    btnNext.Enabled=false;
    btnLast.Enabled=false;
   }

   GoodsByCategoryList.DataSource=pds;
   GoodsByCategoryList.DataBind();

  }

  //计算出该类商品的页总数
  int CountPage()
  {

   EasybuyExcuData count=new EasybuyExcuData();
   int categoryID=Int32.Parse(Request.Params["CategoryID"]);
   DataSet ds=count.GetGoodsCategory(categoryID);

   PagedDataSource pds=new PagedDataSource();
   pds.DataSource=ds.Tables[0].DefaultView;
   pds.AllowPaging=true;
   pds.PageSize=4;

   //返回页面总数
   return pds.PageCount;

  }

  //将对应页码值动态添加至选定控件
  void BindNumDropDownList()
  {
   for(int i=1;i<=CountPage();i++)
   {
    NumberList.Items.Add(i.ToString());
   }
  }

 //向前翻页操作事件
  private void btnFront_Click(object sender, System.EventArgs e)
  {
   PageNum.Text=Convert.ToString(Convert.ToInt32(PageNum.Text)-1);
   BindDataByPage();
   //将默认选定页归1
   NumberList.SelectedValue=PageNum.Text;
  }

  //选定至第一页操作事件
  private void btnFirst_Click(object sender, System.EventArgs e)
  {
   PageNum.Text="1";
   BindDataByPage();
   //将默认选定页归1
   NumberList.SelectedValue=PageNum.Text;
  }

  //下一页事件
  private void btnNext_Click(object sender, System.EventArgs e)
  {
   PageNum.Text=Convert.ToString(Convert.ToInt32(PageNum.Text)+1);
   BindDataByPage();
   //将默认选定页归1
   NumberList.SelectedValue=PageNum.Text;
  }

  //最后一页选定事件
  private void btnLast_Click(object sender, System.EventArgs e)
  {
   //在跳转至末页时必须先计算出页面总数,将其显出来
   PageNum.Text=CountPage().ToString();
   BindDataByPage();

   //将默认选定页归1
   NumberList.SelectedValue=PageNum.Text;

  }


  //当下拉列表选定页码时转至对应选定页
  private void NumberList_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   PageNum.Text=NumberList.SelectedValue;
   BindDataByPage();
  }

同时Page_Load()事件为

  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用代码以初始化页面
   if(!IsPostBack)
   {
    BindDataByPage();
    BindNumDropDownList();
   }
  }

posted on 2006-02-22 01:43  Slash  阅读(1519)  评论(0编辑  收藏  举报