这几天,见网友在问,怎样实现分页?有没有组件?刚好,在做这一个项目,涉及到分页,于是就想发表一下意见。

就分页的技术来看,无非是分两种:

一。通过存储过程来实现

     此点,暂时不讲,因为网上文章很多,迟一下再发表我的意见。

二。通过页面代码来实现

    我之前在网上看到一个文章,说的是为DATALIST分页,用的技术是viewstate保存分页信息,然后再通过这个信息(如当前是第几页,每页多少等)来实现分页。虽然能实现功能,不过,这一点明显是多此一举,究其原因,是由于没有深入认识。NET。其实。NET本身有一个PagedDataSource,它是从GridView里分离出来的分页代码封装,可以轻松实现分页。下面,就以DATALIST作为例子,看一下,他是怎样使用的:

       
以上代码省略
 DataSet ds 
= db.ExecuteDataSet(dbc);
        PagedDataSource pds 
= new PagedDataSource();//初始化分页源
        pds.DataSource = ds.Tables[0].DefaultView;
        pds.PageSize 
= 15;//每页显示的记录数
    
        pds.AllowPaging 
= true;//是否分页


        pds.CurrentPageIndex 
= pageid - 1;//当前页数,因为从0开始,所以接收到的数减1

        DataList1.DataSource 
= pds;//绑定数据源
        DataList1.DataBind();//绑定数据

        
if (pds.IsFirstPage)

            hy1.Visible 
= false;
        
if (pds.IsLastPage)
            hy2.Visible 
= false;
        
int pg;
        
int showp = 10;//显示多少页


       

        
string pgstr;
        pgstr 
= " ";//分页显示代码
        int startp;//开始页数
        int nowp;
        nowp 
= pds.CurrentPageIndex + 1;
        
int totalp;
        totalp 
= pds.PageCount;//得到总页数
        
//   startp = 1;

        
if (nowp % showp == 0)//是否等于上限
        {
            startp 
= pds.CurrentPageIndex + 2;

            
if (totalp > (nowp+showp))
            
{

                pg 
= (nowp+showp);
            }

            
else
                pg 
= totalp;

        }

        
else
        
{
            startp 
= Convert.ToInt16((nowp) / showp) * showp;
            pg 
= startp + showp;

        }



        
if (startp == 0)
        
{
            pg 
= showp;
            startp 
= 1;
        }


      
//  Response.Write(pg);
      
//  Response.End();


        
for (int p = startp; p <= pg; p++)//循环显示页数,并生成相应的URL
        {
            
if ((nowp) == p)
                pgstr 
= pgstr + "    " + p;
            
else
                pgstr 
= pgstr + "    <a href=\"" + Request.CurrentExecutionFilePath + "?PageID=" + Convert.ToString(p) + "&RootID=" + Convert.ToString(root_id) + "\">" + (p) + "</a>";
        }


        fromto.Text 
= pgstr;



        
//  hy1.Text=Request.CurrentExecutionFilePath+"?pageIndex="+Convert.ToString(CurrentPage+1); 

        hy1.NavigateUrl 
= Request.CurrentExecutionFilePath + "?PageID=" + Convert.ToString(pageid - 1+ "&RootID=" + Convert.ToString(root_id);
        hy2.NavigateUrl 
= Request.CurrentExecutionFilePath + "?PageID=" + Convert.ToString(pageid + 1+ "&RootID=" + Convert.ToString(root_id);

        Label1.Text 
= Convert.ToString(pds.PageCount);

以下代码省略



实现的效果图如下: