原创

Repeater百万级数据分页

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://david.blog.csdn.net/article/details/5367114
第一种方法是网络上流行的处理方式

using System;
using System.Data;
using System.Data.SqlClient;

namespace Pagination.Class
{
 /// <summary>
 /// Pager 的摘要说明。
 /// </summary>
 public class Pager
 {
  public Pager()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }
  /// <param name="fieldlist"></param>字段列表,如id,title,content
  /// <param name="condition"></param>条件,如id<100
  /// <param name="pkey"></param>主键,自增
  /// <param name="tablename"></param>表的名字,如News
  /// <param name="sort"></param>排序,0表示降序,1表示升序
  /// <param name="pagesize"></param>每页大小
  /// <param name="cpage"></param>当前页码
  public DataSet GetCurrentDataSet(string fieldlist,string condition,string pkey,string tablename,int sort,int pagesize,int cpage)//得到当前页记录
  {
   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["cs"]);
   SqlDataAdapter cmd=new SqlDataAdapter(GetSql(fieldlist,condition,pkey,tablename,sort,pagesize,cpage),conn);
   DataSet ds=new DataSet();
   cmd.Fill(ds);
   return ds;
  }
  static string GetSql(string fieldlist,string condition,string pkey,string tablename,int sort,int pagesize,int cpage)
  {
   string sql="";
   if(sort==0)
   {
    if(condition!="")
    {
     sql="select top "+pagesize.ToString()+" "+fieldlist+" from "+tablename+" where "+condition+" and "+pkey+" not in(select top "+pagesize*(cpage-1)+" "+pkey+" from "+tablename+" where "+condition+" and order by "+pkey+" desc) order by "+pkey+" desc";
    }
    else
    {
     sql="select top "+pagesize.ToString()+" "+fieldlist+" from "+tablename+" where "+pkey+" not in(select top "+pagesize*(cpage-1)+" "+pkey+" from "+tablename+" order by "+pkey+" desc) order by "+pkey+" desc";
    }
   }
   else
   {
    if(condition!="")
    {
     sql="select top "+pagesize.ToString()+" "+fieldlist+" from "+tablename+" where "+condition+" and "+pkey+" not in(select top "+pagesize*(cpage-1)+" "+pkey+" from "+tablename+" where "+condition+" and order by "+pkey+" asc) order by "+pkey+" asc";
    }
    else
    {
     sql="select top "+pagesize.ToString()+" "+fieldlist+" from "+tablename+" where "+pkey+" not in(select top "+pagesize*(cpage-1)+" "+pkey+" from "+tablename+" order by "+pkey+" asc) order by "+pkey+" asc";
    }
   }
   return sql;
  }
  public int GetCounts(string pkey,string tablename,string condition)//得到总记录数
  {
   string sql;
    if(condition!="")
    {
        sql="select count("+pkey+") from "+tablename where "+condition;
    }
    else
    {
        sql="select count("+pkey+") from "+tablename;
    }
   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["cs"]);
   SqlCommand cmd=new SqlCommand(sql,conn);
   conn.Open();
   SqlDataReader dr=cmd.ExecuteReader(CommandBehavior.CloseConnection);
   dr.Read();
   string str=dr[0].ToString();
   dr.Close();
   return Convert.ToInt32(str);
  }
 }
}
这里可以输出总记录数和当前页面的dataset。

针对此通用分页类的调用实例
1  建表News
CREATE TABLE [News] (
 [id] [int] IDENTITY (1, 1) NOT NULL ,
 [title] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
 [content] [text] COLLATE Chinese_PRC_CI_AS NULL ,
 CONSTRAINT [PK_News] PRIMARY KEY  CLUSTERED 
 (
  [id]
 )  ON [PRIMARY] 
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
2  建立生成数据的存储过程
create proc addnews
@count int
as
declare @i int
set @i=0
set nocount on
while @i<@count
begin
set @i=@i+1
insert into news (title,content) values ('百万级数据分页测试','Test by 逐日★风')
end
set nocount off
GO
3  生成数据
addnews 2000000

4  建立Aspx文件
<asp:Repeater id="Repeater1" runat="server">
 <HeaderTemplate>
  <table width="800" border="1" cellpadding="3">
 </HeaderTemplate>
 <ItemTemplate>
  <tr>
   <td><%#DataBinder.Eval(Container.DataItem,"id")%></td>
   <td><%#DataBinder.Eval(Container.DataItem,"title")%></td>
   <td><%#DataBinder.Eval(Container.DataItem,"content")%></td>
  </tr>
 </ItemTemplate>
 <FooterTemplate>
  </table>
 </FooterTemplate>
</asp:Repeater>
<div align="center"><FONT face="宋体">共</FONT>
 <asp:Label id="lblcount" runat="server"></asp:Label><FONT face="宋体">条记录,当前
  <asp:Label id="lblcurrent" runat="server"></asp:Label>页  
  <asp:LinkButton id="hlprev" runat="server">上页</asp:LinkButton> 
  <asp:LinkButton id="hlnext" runat="server">下页</asp:LinkButton>  
  <asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True"></asp:DropDownList></FONT></div>
5  Cs文件
protected System.Web.UI.WebControls.Label lblcount;
  protected System.Web.UI.WebControls.Label lblcurrent;
  protected System.Web.UI.WebControls.DropDownList DropDownList1;
  protected System.Web.UI.WebControls.LinkButton hlprev;
  protected System.Web.UI.WebControls.LinkButton hlnext;
  protected System.Web.UI.WebControls.Repeater Repeater1;
  private int pagesize=20;
  static int cpage;
  static int TotalPages;

  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!this.IsPostBack)
   {
    cpage=1;
    Class.Pager pg=new Class.Pager();
    int Counts=pg.GetCounts("id","News","");
    lblcount.Text=Counts.ToString();//得到总记录数

    TotalPages=Counts/pagesize;
    if(Counts<pagesize)
     TotalPages=1;
    else
    {
     if(Counts%pagesize!=0)TotalPages++;
    }//计算总页数

    lblcurrent.Text=cpage.ToString()+"/"+TotalPages;
    
    DataSet ds=new DataSet();
    ds=pg.GetCurrentDataSet("id,title,content","","id","News",1,10,cpage);

    bind(ds);
    Gethl();
    Getddlist();
   }
  }
  private void Getddlist()
  {
   if(TotalPages!=1)
   {
    for(int i=1;i<=TotalPages;i++)
    {
     DropDownList1.Items.Add(new ListItem(i.ToString(),i.ToString()));
    }
   }
   else
   {
    DropDownList1.Items.Add(new ListItem("1","1"));
   }
  }
  private void Gethl()//得到上页,下页状态
  {
   if(lblcurrent.Text=="1")
   {
    hlprev.Enabled=false;
    hlnext.Enabled=false;
   }
   else
   {
    if(cpage==1)
     hlprev.Enabled=false;
    else
     hlprev.Enabled=true;
    if(cpage==Convert.ToInt32(TotalPages))
     hlnext.Enabled=false;
    else
     hlnext.Enabled=true;
   }
   lblcurrent.Text=cpage.ToString()+"/"+TotalPages;
  }
  private void bind(DataSet ds)
  {
   Repeater1.DataSource=ds;
   Repeater1.DataBind();
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  ///  设计器支持所需的方法 - 不要使用代码编辑器
  ///  修改此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.hlprev.Click += new System.EventHandler(this.hlprev_Click);
   this.hlnext.Click += new System.EventHandler(this.hlnext_Click);
   this.DropDownList1.SelectedIndexChanged += new System.EventHandler(this.DropDownList1_SelectedIndexChanged);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void hlprev_Click(object sender, System.EventArgs e)
  {
   cpage=cpage-1;
   Class.Pager pg=new Class.Pager();
   DataSet ds=new DataSet();
   ds=pg.GetCurrentDataSet("id,title,content","","id","News",cpage,10,cpage);
   bind(ds);
   Gethl();
   DropDownList1.ClearSelection();
   DropDownList1.Items.FindByValue(cpage.ToString()).Selected=true;
  }

  private void hlnext_Click(object sender, System.EventArgs e)
  {
   cpage=cpage+1;
   Class.Pager pg=new Class.Pager();
   DataSet ds=new DataSet();
   ds=pg.GetCurrentDataSet("id,title,content","","id","News",cpage,10,cpage);
   bind(ds);
   Gethl();
   DropDownList1.ClearSelection();
   DropDownList1.Items.FindByValue(cpage.ToString()).Selected=true;
  }
  private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   cpage=Convert.ToInt32(DropDownList1.SelectedValue);
   Class.Pager pg=new Class.Pager();
   DataSet ds=new DataSet();
   ds=pg.GetCurrentDataSet("id,title,content","","id","News",cpage,10,cpage);
   bind(ds);
   Gethl();
  }

其实重要的是要返回指定页码的的相关数据 没次点击都是重新加载数据

存储过程如下


@OrderField varchar(255),   --排序的字段名
@PageSize int,                 --页尺寸
@PageIndex int,                --页码
@OrderType bit,                --排序类型,1是升序,0是降序
@strWhere varchar(1500),    --查询条件
@Total int output            --返回总记录数
as
declare @strSql varchar(5000)     --主语句
declare @strOrder varchar(200)    --排序
declare @strSqlCount nvarchar(500)--查询记录总数主语句
declare @strtemp varchar(50)      --排序附加语句
--------------排序-----------------1是降序,0未升序
if @OrderType !=0
begin
set @strtemp= '>(select max('
set @strOrder='order by ' + @OrderField + ' asc '
end
else
begin
set @strtemp= '<(select min('
set @strOrder='order by '+ @OrderField + ' desc'
end
--------------总记录数---------------
if @strWhere !=''
begin
set @strSqlCount='Select @TotalCout=count(*) from  ' + @tbName + 'where  '+ @strWhere
end
else
begin
set @strSqlCount='Select @TotalCout=count(*) from  ' + @tbName
end
--------------如果是第一页------------
if @PageIndex =1
begin
if @strWhere !=''
begin
set @strSql = 'Select top' +str(@PageSize)+ ' ' + @tbFields + '  from '+ @tbName +' where ' + @strWhere + ' ' + @strOrder
end
else
begin
set @strSql = 'Select top' +str(@PageSize)+ ' ' + @tbFields + '  from '+ @tbName + ' ' + @strOrder
end
end
else
begin
if @strWhere !=''
begin
set @strSql='Select top ' +str(@PageSize) + ' ' + @tbFields
+' from ' + @tbName + ' where '+@OrderField +' '
+ @strtemp+ ' ' +@OrderField+ ') from (select top'
+str((@PageIndex-1)*@PageSize) + ' '+@OrderField +' from '+@tbName
+ @strWhere+ ' '+ @strOrder +') as tb)'+ @strOrder
end
else
begin
set @strSql='Select top ' + str(@PageSize) + ' ' + @tbFields
+' from ' + @tbName + ' where '+@OrderField + ' '
+ @strtemp+ ' ' +@OrderField+ ') from (select top'
+str((@PageIndex-1)*@PageSize) + ' '+@OrderField +' from '+@tbName
+ ' '+ @strOrder +') as tb)'+ @strOrder
end
end
exec sp_executesql @strSqlCount,N'@TotalCout int output',@Total output
exec(@strSql)

GO

增加一方法
        public DataSet GetCurrentDataSet2(string tbName, string tbFields, string OrderField, int PageSize, int PageIndex, bool OrderType)
        {
            SqlParameter[] parameters = new SqlParameter[8];
            parameters[0] = new  SqlParameter("@tbName", SqlDbType.NVarChar,255);
            parameters[1] = new SqlParameter("@tbFields", SqlDbType.NVarChar, 1000);
            parameters[2] =new SqlParameter("@OrderField", SqlDbType.NVarChar,1000 );
            parameters[3] =new SqlParameter("@PageSize", SqlDbType.Int);
            parameters[4] =new SqlParameter("@PageIndex", SqlDbType.Int);
            parameters[5]=new SqlParameter("@OrderType", SqlDbType.Bit);
            parameters[6] =new SqlParameter("@strWhere", SqlDbType.VarChar,1000);
            parameters[7]=new SqlParameter("@Total", SqlDbType.Int);
 
            parameters[0].Value = tbName;
            parameters[1].Value = tbFields;
            parameters[2].Value = OrderField;
            parameters[3].Value = PageSize;
            parameters[4].Value = PageIndex;
            parameters[5].Value = 1;
            parameters[6].Value = "";
            parameters[7].Value = 0;

            DataAccess.DABaseAccess db = new DABaseAccess();

            return db.RunprocToDataSet("SqlDataPaging", parameters);  //DbHelperSQL.RunProcedure("SqlDataPaging", parameters, "ds");
        }

 

都没有问题。问题是数据到两百万的时候 分页就不触发了。但存储过程是OK的

 
文章最后发布于: 2010-03-11 08:25:00
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 鲸 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览