欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页

程序员文章站 2023-12-13 11:07:16
导言   分页和排序是显示数据时经常用到的功能。比如,在一个在线书店里搜索关于asp.net 的书的时候,可能结果会是成百上千,而每页只列出十条。而且结果可以根据titl...

导言

  分页和排序是显示数据时经常用到的功能。比如,在一个在线书店里搜索关于asp.net 的书的时候,可能结果会是成百上千,而每页只列出十条。而且结果可以根据title(书名),price(价格),page count(页数),author name(作者)等来排序。我们在分页和排序报表数据 里已经讨论过, gridview, detailsview, 和formview 都有内置的分页功能,仅仅只需要勾一个checkbox就可以开启。gridview 还支持内置的排序。

  不幸的是,datalist 和repeater 都没有提供内置的分页和排序功能。本章我们将学习如何在datalist 和repeater 里添加分页和排序的支持。我们需要创建分页界面,显示正确的页的记录,并在postback过程中记下浏览的页。虽然这会比gridview, detailsview, 和formview里花费更多的时间和写更多的代码,但是也提供了更多的可扩展性。

注意:本章集中精力讨论分页,下章我们将学习排序。

第一步: 添加分页和排序的教程页

  首先添加本章和下一章需要的页。创建一个名为pagingsortingdatalistrepeater的文件夹,然后添加下面的5个页,记得全部选择site.master。

default.aspx
paging.aspx
sorting.aspx
sortingwithdefaultpaging.aspx
sortingwithcustompaging.aspx

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 1: 创建页

  然后打开default.aspx页,从usercontrols文件夹里拖一个sectionleveltutoriallisting.ascx用户控件进来。这个用户控件我们已经用了很多次了。见母板页和站点导航  。

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 2: 添加用户控件

  为了将排序和分页的教程列出来,我们需要将他们添加到site map(站点地图)里。打开web.sitemap文件,将下面的标记语言添加到“editing and deleting with the datalist”()的节点后面:

<sitemapnode
 url="~/pagingsortingdatalistrepeater/default.aspx"
 title="paging and sorting with the datalist and repeater"
 description="paging and sorting the data in the datalist and repeater controls">
 <sitemapnode
  url="~/pagingsortingdatalistrepeater/paging.aspx"
  title="paging"
  description="learn how to page through the data shown
      in the datalist and repeater controls." />
 <sitemapnode
  url="~/pagingsortingdatalistrepeater/sorting.aspx"
  title="sorting"
  description="sort the data displayed in a datalist or
      repeater control." />
 <sitemapnode
  url="~/pagingsortingdatalistrepeater/sortingwithdefaultpaging.aspx"
  title="sorting with default paging"
  description="create a datalist or repeater control that is paged using
      default paging and can be sorted." />
 <sitemapnode
  url="~/pagingsortingdatalistrepeater/sortingwithcustompaging.aspx"
  title="sorting with custom paging"
  description="learn how to sort the data displayed in a datalist or
      repeater control that uses custom paging." />
</sitemapnode>

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 3: 更新 site map

回顾一下分页

  在前面我们学习了如何使用gridview, detailsview, formview 来分页。这三个控件都提供了一种称为默认分页的功能,仅仅只需要从智能标签里勾上“enable paging”(开启分页)即可。在使用默认分页时,每次请求数据 – 无论是第一页还是其它页–gridview, detailsview, 和formview 都会重新请求所有的数据。然后根据请求的页索引和每页显示的记录数来显示特定页的数据,而忽略其它数据(即虽然被请求但未显示的数据)。我们在分页和排序报表数据 里已经详细的讨论过默认分页了。

  默认分页由于每次都请求所有的数据,因此在大数据量的情况下并不合适。例如,想象一下每页显示10条数据,总共有有50,000条。每次用户浏览一页时,都要从数据库请求50,000条数据,而其中只有10条会被显示。

  自定义分页使用每次只返回请求的数据,从而解决了默认分页的性能问题。当使用自定义分页时,我们需要写有效的返回正确的记录的sql语句。我们在里学习了用sql server2005的row_number() keyword 来创建这样的语句。

  在datalist或repeater里使用默认分页,我们可以使用pageddatasource class来包装productsdatatable里需要分页的内容。pageddatasource类有一个可以赋给任何枚举类型对象的datasource属性,和pagesize (每页显示的记录数)and currentpageindex (当前页的索引)。一旦设置了这些属性,pageddatasource就可以作为任何数据控件的数据源。pageddatasource根据pagesize和currentpageindex来返回合适的记录。图4描述了pageddatasource类的功能。

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 4: pageddatasource使用可分页的界面包装枚举对象

  pageddatasource对象可以在bll里直接创建和配置,并通过objectdatasource绑定到datalist或repeater。或者也可以在asp.net 页的后台代码里直接做这些。如果使用后一种方法,我们就不能使用objectdatasource而应该直接编程将分页数据绑定到datalist或repeater。

  pageddatasource对象也有支持自定义分页的属性。但是在这里我们将不讨论它,因为我们在productsbll类里已经有一个可以精确的返回需要显示的记录的方法。本章我们将学习如何通过在productsbll类里添加一个返回合适的pageddatasource对象的方法来实现默认分页。下章我们再讨论自定义分页。

第二步: 在bll里添加默认的分页方法

  productsbll类里现在有一个返回所有product的方法–getproducts()–和一个返回特定子集的方法–getproductspaged(startrowindex,maximumrows)。当使用默认分页时,gridview, detailsview, formview 使用getproducts()方法获取所有的product,但是在内部使用pageddatasource来显示正确的记录子集。在datalist和repeater里实现同样的功能,我们可以在bll里创建一个模拟这种行为的方法。

在productsbll里添加一个带两个整型参数的方法,名为getproductsaspageddatasource:

pageindex – 显示的页的索引,从0开始
pagesize – 每页显示的记录数.

  getproductsaspageddatasource首先从getproducts()里获取所有的记录。然后创建一个pageddatasource对象,将currentpageindex和pagesize属性设置为传进来的参数,pageindex和pagesize。方法的最后返回这个配置过的pageddatasource。

[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.select, false)]
public pageddatasource getproductsaspageddatasource(int pageindex, int pagesize)
{
 // get all of the products
 northwind.productsdatatable products = getproducts();
 // limit the results through a pageddatasource
 pageddatasource pageddata = new pageddatasource();
 pageddata.datasource = products.rows;
 pageddata.allowpaging = true;
 pageddata.currentpageindex = pageindex;
 pageddata.pagesize = pagesize;
 return pageddata;
}

第三步: 在datalist里使用默认分页显示product

  完成getproductsaspageddatasource方法后,我们现在来创建一个提供默认分页的datalist或repeater。打开pagingsortingdatalistrepeater文件夹下的paging.aspx页,拖一个datalist进来,将id设为productsdefaultpaging。通过智能标签创建一个名为productsdefaultpagingdatasource的objectdatasource并用getproductsaspageddatasource方法配置它。

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 5: 创建并配置objectdatasource

在update, insert, delete 标签的下拉列表里都选择“(none)”.

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 6: 在update, insert, delete 标签的下拉里选择“(none)”

  因为getproductsaspageddatasource方法需要两个参数,因此向导会提示我们选择参数源。page index和page size的值必须在postback过程中记下来。它们可以存在view state,querystring,session里或用其它技术来记录。本章我们使用querystring。

  分别使用querystring字段“pageindex” 和“pagesize”来配置pageindex和pagesize。见图7。由于用户第一次浏览页的时候没有querystring,因此还需要设置这两个参数的默认值。将pageindex的默认值设为0(表示显示第一页数据),将pagesize的默认值设为4。

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 7: 配置参数

  配置完objectdatasource后,visual studio自动为datalist创建一个itemtemplate。修改它让它只显示product的name,category和supplier。将datalist的repeatcolumns属性设为2,width设为“100%”, itemstyle的width设为 “50%”. 这样的设置会为两列提供相同的间距。完成这些后datalist和objectdatasource的标记语言看起来应该如下:

<asp:datalist id="productsdefaultpaging" runat="server" width="100%"
 datakeyfield="productid" datasourceid="productsdefaultpagingdatasource"
 repeatcolumns="2" enableviewstate="false">
 <itemtemplate>
  <h4><asp:label id="productnamelabel" runat="server"
   text='<%# eval("productname") %>'></asp:label></h4>
  category:
  <asp:label id="categorynamelabel" runat="server"
   text='<%# eval("categoryname") %>'></asp:label><br />
  supplier:
  <asp:label id="suppliernamelabel" runat="server"
   text='<%# eval("suppliername") %>'></asp:label><br />
  <br />
  <br />
 </itemtemplate>
 <itemstyle width="50%" />
</asp:datalist>
<asp:objectdatasource id="productsdefaultpagingdatasource" runat="server"
 oldvaluesparameterformatstring="original_{0}" typename="productsbll"
 selectmethod="getproductsaspageddatasource">
 <selectparameters>
  <asp:querystringparameter defaultvalue="0" name="pageindex"
    querystringfield="pageindex" type="int32" />
  <asp:querystringparameter defaultvalue="4" name="pagesize"
    querystringfield="pagesize" type="int32" />
 </selectparameters>
</asp:objectdatasource>

注意:由于这里我们不实现任何更新或删除的功能,你可以禁用datalist的view state来减少页面的大小。

  第一次浏览页的时候,querystring里没有提供pageindex 和pagesize的值,因此将使用默认的0和4。见图8。datalist将显示4条product记录。

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 8: 显示4条product

  由于还没有分页的界面,因此用户现在还不能直接导航到第二页。我们将在第四步里创建分页界面。现在我们只能直接在querystring里指定分页的参数来进行分页。例如,我们可以将地址从paging.aspx改为paging.aspx?pageindex=2,然后回车,来浏览第二页。这样就可以看到第二页的数据了,见图9。

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 9: 显示第二页数据

第四步: 创建分页界面

有很多不同的完成分页界面的方法。gridview, detailsview, formview 提供了4种不同的界面:

next, previous(后一页,前一页) – 用户可以浏览上一页或下一页.
next, previous, first(第一页), last (最后一页)– 除了上面的功能,这个还包含第一页和最后一页。
numeric (数字)–在分页界面上列出页数,用户可以随意的选择一个页 .
numeric, first, last – 在上一个功能的基础上增加了第一页和最后一页.

  对datalist 和repeater而言,我们需要决定它的分页界面并实现它。这其中包含了需要创建web控件和当特定页的button被点时显示请求的页。另外某些分页界面的控件可能需要禁用。例如,当使用next, previous, first, last这个模式来显示时,如果浏览第一页数据,那么第一页和前一页的button应该被禁用。

  本章我们使用 next, previous, first, last界面。添加4个button,并将id分别设为firstpage,prevpage,nextpage和lastpage。将text设为“<< first”, “< prev”, “next >”, “last >>”.

<asp:button runat="server" id="firstpage" text="<< first" />
<asp:button runat="server" id="prevpage" text="< prev" />
<asp:button runat="server" id="nextpage" text="next >" />
<asp:button runat="server" id="lastpage" text="last >>" />

然后为每个button创建一个click事件处理。呆会我们将添加代码来显示请求的页。

记下分页的总记录数

  不管选择哪种分页界面,我们都需要计算和记下分页的总记录数。总的行数(和page size)来决定总的页数,它决定了那些分页界面的控件需要增加或启用。在我们创建的next, previous, first, last 界面里,page count(页数)在两种情况下需要被用到:

  判断我们是否在浏览最后一页,这种情况下next 和last buttons 需要禁用。
  如果用户点了last button我们需要将它转到最后一页,它的索引等于page count减1。

  page count通过总行数除以page size(页数)来计算得到。例如我们要分页79条记录,每页显示4条,那么page count为20(79/4)。如果我们使用数字分页界面,就可以通过这个信息来决定要显示多少个数字页的button。如果分页界面只包含next 和last buttons,可以通过page count来什么时候禁用next 和last buttons。

  如果分页界面包含last button(最后一页),我们需要在postback过程中记下分页的总记录数,这样在点last button的时候我们可以获得最后一页的索引。为了方便实现这个,我们在asp.net页的后台代码里创建一个totalrowcount属性来将这个值保存到view state里。

private int totalrowcount
{
 get
 {
  object o = viewstate["totalrowcount"];
  if (o == null)
   return -1;
  else
   return (int)o;
 }
 set
 {
  viewstate["totalrowcount"] = value;
 }
}

  除了totalrowcount外,还需要为page index,page size和page count创建页面级的只读属性来方便读取。

private int pageindex
{
 get
 {
  if (!string.isnullorempty(request.querystring["pageindex"]))
   return convert.toint32(request.querystring["pageindex"]);
  else
   return 0;
 }
}
private int pagesize
{
 get
 {
  if (!string.isnullorempty(request.querystring["pagesize"]))
   return convert.toint32(request.querystring["pagesize"]);
  else
   return 4;
 }
}
private int pagecount
{
 get
 {
  if (totalrowcount <= 0 || pagesize <= 0)
   return 1;
  else
   return ((totalrowcount + pagesize) - 1) / pagesize;
 }
}

获取分页的总记录数

  从objectdatasource的select()方法返回一个pageddatasource对象包含所有的product记录,即使只有一部分会在datalist里显示。pageddatasource的count property 返回将在datalist里显示的项的数目。datasourcecount property 返回pageddatasource里的所有项的的总数目。因此我们需要将asp.net页的totalrowcount属性赋值为pageddatasource的datasourcecount。

  我们为objectdatasource的selectd事件创建一个event handler来完成这些。在selectd的event handler里我们获取objectdatasource的select()方法的返回值–在这种情况下是pageddatasource。

protected void productsdefaultpagingdatasource_selected
 (object sender, objectdatasourcestatuseventargs e)
{
 // reference the pageddatasource bound to the datalist
 pageddatasource pageddata = (pageddatasource)e.returnvalue;
 // remember the total number of records being paged through
 // across postbacks
 totalrowcount = pageddata.datasourcecount;
}

显示请求的页的数据

  当用户点分页界面上的button时,我们需要显示请求的页的数据。由于分页的参数在querystring里指定,因此使用response.redirect(url)来让用户重新请求带合适分页参数的paging.aspx页。例如,显示第二页的数据,我们将用户重定向到paging.aspx?pageindex=1。

  创建一个redirectuser(sendusertopageindex)方法来重定向用户到paging.aspx?pageindex=sendusertopageindex。然后在四个按钮的click事件处理里调用这个方法。在firstpageclick里调用redirectuser(0),在prevpageclick里调用redirectuser(pageindex-1)。

protected void firstpage_click(object sender, eventargs e)
{
 // send the user to the first page
 redirectuser(0);
}
protected void prevpage_click(object sender, eventargs e)
{
 // send the user to the previous page
 redirectuser(pageindex - 1);
}
protected void nextpage_click(object sender, eventargs e)
{
 // send the user to the next page
 redirectuser(pageindex + 1);
}
protected void lastpage_click(object sender, eventargs e)
{
 // send the user to the last page
 redirectuser(pagecount - 1);
}
private void redirectuser(int sendusertopageindex)
{
 // send the user to the requested page
 response.redirect(string.format("paging.aspx?pageindex={0}&pagesize={1}",
  sendusertopageindex, pagesize));
}

  完成click事件处理后,datalist的记录现在可以通过button来分页了,你可以测试一下。

禁用分页控件

  现在无论浏览哪页四个按钮都是可用的。然而我们在浏览第一页时需要禁用 first 和previous buttons ,在浏览最后一页时需要禁用next 和last buttons。通过objectdatasource的select()方法返回的pageddatasource对象有几个属性– isfirstpage 和 islastpage –通过它们可以判断用户浏览的是否是第一或最后一页数据。添加下面的代码到objectdatasource的selected事件处理里:

// configure the paging interface based on the data in the pageddatasource
firstpage.enabled = !pageddata.isfirstpage;
prevpage.enabled = !pageddata.isfirstpage;
nextpage.enabled = !pageddata.islastpage;
lastpage.enabled = !pageddata.islastpage;

  添加完后,当浏览第一页时,first 和previous buttons 将被禁用。当浏览最后一页时,next 和  last buttons 将被禁用。

  我们最后来实现在分页界面里通知用户他们当前是浏览的哪页和一共有多少页。添加一个label控件并将id设为currentpagenumber。在objectdatasource的selected事件处理中设置它的text属性,让它显示当前浏览的页(pageindex+1)和总页数(pagecount)。

// display the current page being viewed...
currentpagenumber.text = string.format("you are viewing page {0} of {1}...",
 pageindex + 1, pagecount);

  图10是第一次浏览paging.aspx页的样子。由于querystring是空的,因此datalist默认显示最开始的4条product。first 和previous buttons 被禁用。点next 会显示下面的4条记录(见图11),而first 和previous buttons 同时被启用了。

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 10: 第一页数据

在ASP.NET 2.0中操作数据之四十一:DataList和Repeater数据分页
图 11: 第二页数据

  注意:分页界面可以进一步改善,比如增加允许用户来指定每页显示多少记录。例如添加一个dropdownlist列出page size的选项,比如5, 10, 25, 50, 和all。用户选择了page size后会重定向到paging.aspx?pageindex=0&pagesize=selectedpagesize。我将这个作为练习留给读者自己完成。

使用自定义分页

  datalist使用没有效率的默认分页技术。当大数据量时,我们需要使用自定义分页。虽然实现的细节有所不同,但是分页里的概念和默认分页是一样的。默认分页时,使用productsbll类的getproductspaged方法(而不是getproductsaspageddatasource)。正如在大数据量时提高分页的效率 里讨论的那样,getproductspaged需要传入开始行的索引和行的最大数目。这些参数可以通过默认分页里使用的querystring里的pageindex和pagesize参数来保存。

  由于自定义分页里没有pageddatasource,所以需要其它技术来决定总记录数和判断我们是否显示第一或最后一页数据。productsbll类的totalnumberofproducts()方法返回roduct的总记录数。而为了判断是否浏览的是第一页数据,我们需要检查开始行的索引–如果是0,则表示在浏览第一页。如果开始行的索引加上最大的行数大于或等于总记录数则表示在最后一页.我们将在下章详细的讨论如何实现自定义分页。

总结

  datalist和repeater都没有提供象gridview, detailsview, formview 那样的分页的支持,这样的功能需要我们来实现。最简单的实现方法是使用默认分页,将所有的product都包装到pageddatasource里,然后绑定pageddatasource到datalist或repeater。本章我们在productsbll类里添加getproductsaspageddatasource方法,它返回pageddatasource。productsbll类已经包含了自定义分页需要的方法– getproductspaged和totalnumberofproducts。

  不管是自定义方法里获取精确的记录还是默认方法里获取所有记录,我们都需要手动添加分页界面。本章我们创建的是包含4个button控件的next, previous, first, last interface 。当然还添加了一个显示当前页和总页数的label控件。

  下章将学习如何为datalist和repeater提供排序功能。我们也会创建一个既支持分页又支持排序的datalist(和使用默认和自定义分页的例子)

  祝编程快乐!

作者简介

  本系列教程作者 scott mitchell,著有六本asp/asp.net方面的书,是4guysfromrolla.com的创始人,自1998年以来一直应用 微软web技术。大家可以点击查看全部教程《[翻译]scott mitchell 的asp.net 2.0数据教程》,希望对大家的学习asp.net有所帮助。

上一篇:

下一篇: