利用ASP.NET实现分页管理器

DataGrid的web版控件中提供了自动分页的功能,但是我从来没用过它,因为它实现的分页只是一种假相。我们为什么需要分页?那是因为符合条件的记录可能很多,如果一次读取所有的记录,不仅延长获取数据的时间,而且也极度浪费内存。而分页的存在的主要目的正是为了解决这两个问题(当然,也不排除为了UI美观的需要而使用分页的)。而web版的DataGrid是怎样实现分页的了?它并没有打算解决上述两个问题,而还是一次读取所有的数据,然后以分页的样子表现出来。这是对效率和内存的极大损害!

  于是我自己实现了分页管理器IPaginationManager ,IPaginationManager 每次从数据库中读取指定的任意一页,并且可以缓存指定数量的page。这个分页管理器的主要特点是:

  (1)支持随机跳转。这是通过嵌套Select语句实现的。

  (2)支持缓存。通过EnterpriseServerBase.DataStructure.FixCacher进行支持。

  先来看看IPaginationManager接口的定义:

public interface IPaginationManager
{
  void Initialize(DataPaginationParas paras) ;
  void Initialize(IDBAccesser accesser ,int page_Size ,string whereStr ,string[] fields) ; //如果选择所有列, fields可传null

  DataTable GetPage(int index) ; //取出第index页
  DataTable CurrentPage() ;
  DataTable PrePage() ;
  DataTable NextPage() ;

  int PageCount{get ; }
  int CacherSize{get; set; }
}
这个接口定义中,最主要的是GetPage()方法,实现了这个方法,其它的三个获取页面的方法CurrentPage、PrePage、 NextPage也就非常容易了。另外,CacherSize属性可以让我们指定缓存页面的数量。如果不需要缓存,则设置其值<=0,如果需要无限缓存,则值为Int.MaxValue。

  IPaginationManager接口中的第二个Initialize方法,你不要关心,它是给XCodeFactory生成的数据层使用了,我们来看看第一个Initialize方法的参数类型DataPaginationParas的定义:

public class DataPaginationParas
{
  public int PageSize = 10 ;
  public string[] Fields = {"*"}; //要搜索出的列,"*"表示所有列

  public string ConnectString ;
  public string TableName ;
  public string WhereStr ; //搜索条件的where字句

  public DataPaginationParas(string connStr ,string tableName ,string whereStr)
  {
  this.ConnectString = connStr ;
  this.TableName = tableName ;
  this.WhereStr = whereStr ;
  }

  #region GetFiedString
  public string GetFiedString()
  {
  if(this.Fields == null)
  {
  this.Fields = newstring[] {"*"} ;
  }

  string fieldStrs = "" ;

  for(int i=0 ; i  {
  fieldStrs += " " + this.Fields ;
  if(i != (this.Fields.Length -1))
  {
  fieldStrs += " , " ;
  }
  else
  {
  fieldStrs += " " ;
  }
  }

  return fieldStrs ;
  }
  #endregion

}

  DataPaginationParas.GetFiedString用于把要搜索的列形成字符串以便嵌入到SQL语句中。DataPaginationParas中的其它字段的意思都很明显。


现在来看看分页管理器的实现了:

public class PaginationManager :IPaginationManager
{
  private DataPaginationParas theParas ;
  private IADOBase adoBase ;
  private DataTable curPage = null ;
  private int itemCount = 0 ;
  private int pageCount = -1 ;
  private int curPageIndex = -1 ;

  private FixCacher fixCacher = null ;
  private string fieldStrs = "" ;

  ///
  /// cacheSize 小于等于0 -- 表示不缓存 ,Int.MaxValue -- 缓存所有
  ///
  public PaginationManager(int cacheSize)
  {
  if(cacheSize == int.MaxValue)
  {
  this.fixCacher = new FixCacher() ;
  }
  else if(cacheSize >0)
  {
  this.fixCacher = new FixCacher(cacheSize) ;
  }
  else
  {
  this.fixCacher = null ;
  }
  }

  public PaginationManager()
  {}

  #region IDataPaginationManager 成员
  public int CacherSize
  {
  get
  {
  if(this.fixCacher == null)
  {
  return 0 ;
  }
  return this.fixCacher.Size ;
  }
  set
  {
  if(this.fixCacher == null)
  {
  this.fixCacher = new FixCacher(value) ;
  }
  else
  {
  this.fixCacher.Size = value ;
  }
  }
  }
  public int PageCount
  {
  get
  {
  if(this.pageCount == -1)
  {
  string selCountStr = string.Format("Select count(*) from {0} {1}" ,this.theParas.TableName ,this.theParas.WhereStr) ;
  DataSet ds= this.adoBase.DoQuery(selCountStr) ;
  this.itemCount = int.Parse(ds.Tables[0].Rows[0][0].ToString()) ;
  this.pageCount = this.itemCount/this.theParas.PageSize ;
  if((this.itemCount%this.theParas.PageSize >0))
  {
  ++ this.pageCount ;
  }
  }
  return this.pageCount ;
  }
  }

  ///
  /// GetPage 取出指定的一页
  ///
  public DataTable GetPage(int index)
  {
  if(index == this.curPageIndex)
  {
  return this.curPage ;
  }

  if((index < 0) || (index >(this.PageCount-1)))
  {
  return null;
  }

  DataTable dt = this.GetCachedObject(index) ;

  if(dt == null)
  {
  string selectStr = this.ConstrutSelectStr(index) ;
  DataSet ds = this.adoBase.DoQuery(selectStr) ;
  dt = ds.Tables[0] ;

  this.CacheObject(index ,dt) ;
  }
  this.curPage = dt ;
  this.curPageIndex = index ;
  return this.curPage ;
  }

  private DataTable GetCachedObject(int index)
  {
  if(this.fixCacher == null)
  {
  return null ;
  }
  return (DataTable)this.fixCacher[index] ;
  }

  private void CacheObject(int index ,DataTable page)
  {
  if(this.fixCacher != null)
  {
  this.fixCacher.PutIn(index ,page) ;
  }
  }

  public DataTable CurrentPage()
  {
  return this.curPage ;
  }

  public DataTable PrePage()
  {
  return this.GetPage((--this.curPageIndex)) ;
  }

  public DataTable NextPage()
  {
  return this.GetPage((++this.curPageIndex)) ;
  }

  private string ConstrutSelectStr(int pageIndex)
  {
  if(pageIndex == 0)
  {
return string.Format("Select top {0} {1} from {2} {3} ORDER BY ID" ,this.theParas.PageSize ,this.fieldStrs ,this.theParas.TableName ,this.theParas.WhereStr) ;
  }

int innerCount = this.itemCount - this.theParas.PageSize*pageIndex ;
string innerSelStr = string.Format("Select top {0} {1} from {2} {3} ORDER BY ID DESC " ,innerCount , this.fieldStrs ,this.theParas.TableName ,this.theParas.WhereStr) ;
  string outerSelStr = string.Format("Select top {0} * from ({1}) DERIVEDTBL ORDER BY ID" ,this.theParas.PageSize ,innerSelStr) ;

  return outerSelStr ;
  }

  #region Initialize
  public void Initialize(IDBAccesser accesser, int page_Size, string whereStr, string[] fields)
  {
  this.theParas = new DataPaginationParas(accesser.ConnectString ,accesser.DbTableName ,whereStr) ;
  this.theParas.Fields = fields ;
  this.theParas.PageSize = page_Size ;

  this.fieldStrs = this.theParas.GetFiedString() ;
  this.adoBase = new SqlADOBase(this.theParas.ConnectString) ;
  }

  public void Initialize(DataPaginationParas paras)
  {
  this.theParas = paras ;
  this.fieldStrs = this.theParas.GetFiedString() ;
  this.adoBase = new SqlADOBase(this.theParas.ConnectString) ;
  }

  #endregion
  #endregion
}
  了解这个类的实现,可以从GetPage(int index)方法入手,另外私有方法ConstrutSelectStr()的实现说明了如何使用嵌套sql语句进行随机分页搜索。

  最后,关于分页管理器,需要指出的是,搜索对应的表必须有一个名为"ID"的主键--这是唯一的要求。另外,分页管理器实现用到的数据访问低阶封装IADOBase定义于EnterpriseServerBase类库中。

  使用分页管理器是很简单的,加上UI界面后,只要把返回的DataTable绑定到DataGrid就可以了。

主從DataGrid的顯示<asp:datagrid id="DataGrid1" ShowHeader =false AutoGenerateColumns =true runat="server" DataKeyField="OrderId" >

    <Columns>

          <asp:TemplateColumn >

              <ItemTemplate>

                    <b><%#DataBinder.Eval(Container.DataItem,"OrderId")%></b>

              </ItemTemplate>

          </asp:TemplateColumn>

    </Columns>

</asp:datagrid>




SqlConnection cn;

SqlDataAdapter da;

DataSet ds;

private void Page_Load(object sender, System.EventArgs e)

{

    // Put user code to initialize the page here

    cn= new SqlConnection ("Server=localhost;uid=sa;pwd=;database=northwind");

    if (!Page.IsPostBack)

    {

          da= new SqlDataAdapter ("SELECT orderid FROM orders ", cn);

          ds= new DataSet ();

          da.Fill (ds, "Orders");

          DataGrid1.DataSource = ds;

          DataGrid1.DataBind ();

    }

}



protected void ItemDB(Object sender,DataGridItemEventArgs e )

{

    if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem ))

    {

          DataGrid dgDetails = new DataGrid();

          int orderid =(int) ((DataRowView)e.Item.DataItem)["OrderID"] ;

          dgDetails.DataSource = GetOrderDetails(orderid );

          dgDetails.DataBind();

          e.Item.Cells[1].Controls.Add(dgDetails);

    }

}



DataSet GetOrderDetails(int id )

{

    da= new SqlDataAdapter ("SELECT * FROM [Order Details] where orderid= " + id, cn);

    ds= new DataSet ();

    da.Fill (ds, "OrderDetails");

    return ds;

}

Datagrid自动增加编号列号
内容

1
Taye

2
BOx

3
Glass

4
StarCraft


一、正序
A、AllowPaging=False情况下,使用以下方法就可以实现:

1<asp:DataGrid id=DataGrid1 runat=server>
2    <Columns>
3    <asp:TemplateColumn>
4      <ItemTemplate>
5      <%# Container.ItemIndex + 1%>
6      </ItemTemplate>
7    </asp:TemplateColumn>
8    </Columns>
9 </asp:DataGrid>

不过更有趣的方法是使用这个方法:


1<asp:DataGrid id=DataGrid1 runat=server>
2    <Columns>
3    <asp:TemplateColumn>
4      <ItemTemplate>
5      <%# this.DataGrid1.Items.Count + 1%>
6      </ItemTemplate>
7    </asp:TemplateColumn>
8    </Columns>
9</asp:DataGrid>

也许有些人会觉得很奇怪为什么Items.Count会这样,而不是出来全部总合,但如果你了解绑定的过程时就容易理解。[从上面来看就是在ItemCreated事件中进行绑定所以得到的Items.Count刚好是当前的序号]

B、AllowPaging=True下,如果DataGrid支持分页则可以如下:

1<asp:DataGrid id=DataGrid1 runat=server AllowPaging=True>
2    <Columns>
3    <asp:TemplateColumn>
4      <ItemTemplate>
5      <%# this.DataGrid1.CurrentPageIndex * this.DataGrid1.PageSize + Container.ItemIndex + 1%>
6      </ItemTemplate>
7    </asp:TemplateColumn>
8    </Columns>
9</asp:DataGrid>

二、倒序的方法

序号
内容

4
Taye

3
BOx

2
Glass

1
StarCraft


由上面可以知道使用this.DataGrid1.Items.Count - Container.ItemIndex + 1方法是不可能实现的,得到值而且全会为1,分页的情况下更是一样.所以一开始我们就要取得数据源的行数:


1private int rowscount = 0;
2        protected int RowsCount
3        {
4              get{ return rowscount;}
5              set{ this.rowscount = value; }
6        }
7   
8        private void Page_Load(object sender, System.EventArgs e)
9        {
10              // 在此处放置用户代码以初始化页面
11              if(!IsPostBack)
12                  this.BindData();
13        }
14        private void BindData()
15        {
16              SqlConnection cn = new SqlConnection(server=(local);database=NorthWind;uid=sa;pwd=);
17              string str=@SELECT Employees.EmployeeID, Orders.EmployeeID
18                                FROM Employees INNER JOIN
19                      Orders ON Employees.EmployeeID = Orders.EmployeeID ;
20              SqlDataAdapter sqlda = new SqlDataAdapter(str,cn);
21              DataSet ds = new DataSet();
22              sqlda.Fill(ds);
23              this.RowsCount = ds.Tables[0].Rows.Count;
24              this.DataGrid1.DataSource = ds;
25              this.DataGrid1.DataBind();
26}


1<asp:DataGrid id=DataGrid1 runat=server AllowPaging=True>
2                            <Columns>
3                                  <asp:TemplateColumn>
4                                          <ItemTemplate>
5                                                <%# RowsCount - DataGrid1.CurrentPageIndex * DataGrid1.PageSize - Container.ItemIndex %>
6                                          </ItemTemplate>
7                                  </asp:TemplateColumn>
8                            </Columns>
9                    </asp:DataGrid>
、哭┈゛.並不代表Wo屈服х. 退一步...並不象徵Wo認輸..→.放手.ǐ.o.並不表示Wo放棄.正如Wo微笑.並不意味Wo快樂┈┊