网络编程
位置:首页>> 网络编程>> ASP.NET>> ASP.NET 2.0中Gridview控件高级技巧图文教程(2)

ASP.NET 2.0中Gridview控件高级技巧图文教程(2)

作者:廖煜嵘 来源:天极网 发布时间:2007-08-07 15:46:00 

标签:ASP.NET,Gridview,技巧,2.0

二 gridview的分页和排序

  在asp.net 1.1中,datagrid分页是很常见的。 
  
而在asp.net 2.0中,依然有两种分页方式,一种是默认的分页方式,比如,有1000条数据,每页显示10条数据,则每次页面请求都必须从数据库中将1000条数据读取出来,只不过每次显示一页时,显示10条数据,速度和性能会降低。另一种是自定义分页方式,比如1000条数据,每页显示10条数据,则程序每次在页面跳转时,只会从数据库中拿10条数据出来显示给用户,而不是每次都把1000条数据拿出来,因此性能大为提高。

  在asp.net 2.0中,使用sqldatasource控件进行分页是十分容易的事情。Sqldatasource数据源控件是用来与数据库打交道的,可以读取数据库中的数据,并可以和gridview等控件进行绑定。在下面的演示中,首先拖拉一个sqldatasource控件,并且设置其数据源为sql server 中的northwind数据库,再拖拉一个gridview控件,并且点gridview的smart tag智能标记,在弹出的菜单中,选择"enable paging"和"enable sorting",即允许分页和排序,则可以完成分页和排序的功能了,是不是很简单呢?如下图所示:




  而在分页的效果中,有时我们想让用户知道,目前正在浏览的是第几页,那么要如何实现呢?在gridview中,有一个pageindex的属性,指示页面的序号(从0开始),则只需在页面的html代码内,写下如下代码,即可实现效果:

<i>You are viewing page
<%=productsGridView.PageIndex + 1%>
of
<%=productsGridView.PageCount%>
</i>


 完整代码如下:

<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="productDataSource" Runat="server" 
 SelectCommand="SELECT [ProductName], [UnitPrice], 
 [UnitsInStock], [QuantityPerUnit] FROM [Products]"
 ConnectionString="<%$ ConnectionStrings:NWConnectionString %>">
  </asp:SqlDataSource>
  <asp:GridView ID=" productsGridView" Runat="server" 
    DataSourceID="productDataSource" AutoGenerateColumns="False"
    AllowSorting="True" BorderWidth="2px" BackColor="White" GridLines="None" CellPadding="3"
    CellSpacing="1" BorderStyle="Ridge" BorderColor="White" AllowPaging="True">
   <FooterStyle ForeColor="Black" BackColor="#C6C3C6"></FooterStyle>
   <PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#C6C3C6"></PagerStyle>
   <HeaderStyle ForeColor="#E7E7FF" Font-Bold="True" BackColor="#4A3C8C"></HeaderStyle>
   <Columns>
   <asp:BoundField HeaderText="Product" DataField="ProductName" SortExpression="ProductName">
  </asp:BoundField>
  <asp:BoundField HeaderText="Unit Price" DataField="UnitPrice" SortExpression="UnitPrice"
DataFormatString="{0:c}">
   <ItemStyle HorizontalAlign="Right"></ItemStyle>
  </asp:BoundField>
  <asp:BoundField HeaderText="Units In Stock" DataField="UnitsInStock" 
SortExpression="UnitsInStock" DataFormatString="{0:d}">
   <ItemStyle HorizontalAlign="Right"></ItemStyle>
  </asp:BoundField>
  <asp:BoundField HeaderText="Quantity Per Unit" DataField="QuantityPerUnit"></asp:BoundField>
 </Columns>
 <SelectedRowStyle ForeColor="White" Font-Bold="True" BackColor="#9471DE"></SelectedRowStyle>
 <RowStyle ForeColor="Black" BackColor="#DEDFDE"></RowStyle>
</asp:GridView>
<i>You are viewing page
<%=productsGridView.PageIndex + 1%>
of
<%=productsGridView.PageCount%>
</i>
</div>
</form>


实现的效果如下图所示:


  注意的是,可以点击gridview中各字段的名称,如product,unit price,等进行排序,十分方便。如果要对分页时每页显示多少条数据进行显示,则只需要设置gridview的pagesize属性就可以了。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com