在ASP.NET 2.0中操作数据之四十二:DataList和Repeat

  DataList和Repeater数据分页里我们学习了如何在DataList里添加分页功能。我们在ProductsBLL类里创建了一个名为GetProductsAsPagedDataSource的方法,它返回一个PagedDataSource对象。当绑定到DataList或Repeater时,他们将只显示请求页的数据。这个技术和GridView,DetailsView,FormView的内置分页功能原理差不多。

  除了分页外,GridView还提供了内置的排序功能,而DataList和Repeater都没有。然而排序功能可以通过一点点代码就实现。本章我们将学习如何在DataList和Repeater里实现排序功能,我们还将创建一个同时支持分页和排序的DataList或Repeater。

回顾一下排序

  如我们在分页和排序报表数据里看到的,GridView提供了排序的支持。每个GridView的字段可以有一个关联的SortExpression,它指明了对数据进行排序依据的字段。当GridView的AllowSorting属性设为true时,每个包含SortExpression 属性的GridView的字段的header都表现为一个LinkButton。当点一个header时,页面postback,数据会根据被点字段的SortExpression进行排序。另外,SortDirection属性指明了数据是升序或降序。

  当将GridView绑定到数据源控件时,它会将SortExpression和SortDirection传给数据源控件。数据源控件获取数据并根据SortExpression和SortDirection进行排序。然后将数据返回给GridView。

在DataList或Repeater里实现这个功能,我们需要: 

  创建一个排序界面
  将排序的字段和方向(升序或降序)记下
  指导ObjectDataSource根据特定字段排序

  我们将在第三和四步来处理上面三个步骤。然后我们将看看如何让DataList或Repeater同时支持这两个功能(分页和排序)。

第二步: 在 Repeater里显示 Products

  在实现排序功能前,首先创建一个列出所有product的Repeater。打开PagingSortingDataListRepeater文件夹里的Sorting.aspx页。添加一个Repeater,将ID设为SortableProducts。从智能标签里创建一个名为ProductsDataSource的ObjectDataSource。用ProductsBLL类的GetProducts()方法配置它。在INSERT, UPDATE, DELETE标签的下拉列表里选择“(None)”。

/uploads/allimg/200612/1IIJ106_0.png


图 1: 创建 ObjectDataSource

/uploads/allimg/200612/1IIOZ6_0.png


图 2: 在 UPDATE, INSERT, DELETE 标签的下拉列表里选择 “(None)”

  在绑定到数据源后,Visual Studio没有自动为Repeater创建ItemTemplate,这点和DataList不一样。而且由于Repeater控件的智能标签里没有象DataList里那样的“Edit Templates”选项,因此我们需要直接添加声明代码。我们使用和前一章一样的ItemTemplate,它显示product的 name, supplier, category。

  现在你的Repeater和ObjectDataSource的声明标记看起来应该和下面差不多:

<asp:Repeater DataSourceID="ProductsDataSource" EnableViewState="False" runat="server"> <ItemTemplate> <h4><asp:Label runat="server" Text='<%# Eval("ProductName") %>'></asp:Label></h4> Category: <asp:Label runat="server" Text='<%# Eval("CategoryName") %>'></asp:Label><br /> Supplier: <asp:Label runat="server" Text='<%# Eval("SupplierName") %>'></asp:Label><br /> <br /> <br /> </ItemTemplate> </asp:Repeater> <asp:ObjectDataSource runat="server" OldValuesParameterFormatString="original_{0}" TypeName="ProductsBLL" SelectMethod="GetProducts"> </asp:ObjectDataSource>

图 3 是现在浏览该页的样子。

/uploads/allimg/200612/1IIME1_0.png


图 3: 显示 Product的 Name, Supplier, Category

第三步: 指导 ObjectDataSource 对数据进行排序

  为了让Repeater里显示的数据排序,我们需要将数据排序的sort expression告诉ObjectDataSource。在ObjectDataSource获取数据前,首先激发的是Selecting event,它给我们提供了一个指定sort expression的机会。Selecting event handler 有一个ObjectDataSourceSelectingEventArgs 类型的参数,它有一个名为Arguments的 DataSourceSelectArguments类型的属性.。DataSourceSelectArguments类被设计用来将数据相关的请求从数据的消费者传给数据源控件,它有一个SortExpression property。

  创建一个Selecting event handler,用以下代码将排序的信息从ASP.NET页传给ObjectDataSource:

protected void ProductsDataSource_Selecting (object sender, ObjectDataSourceSelectingEventArgs e) { e.Arguments.SortExpression = sortExpression; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwyxj.html