二 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属性就可以了。