设为首页
加入收藏
站内地图
旧版入口
当前位置:首页 > 站长学院 > 网络编程 > ASP.NET

ASP.NET 2.0中Gridview控件高级技巧2

作者:佚名 出处:网络转载 时间:11-08 点击:

内容载入中...
     二 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属性就可以了。
    。

收藏本文:
】【打印页面】【推荐给朋友】【关闭窗口

站长学院

推荐信息