1.使用数据源控件可以自动做排序分页,不需要多余代码,可是由于自动绑定太多操作,反而觉得很不灵活
前台:
<asp:GridViewID="gv_test"DataSourceID="ds_test"AllowPaging="True" PageSize="10"runat="server">
...
</asp:GridView>
<asp:SqlDataSource runat="server" ID="ds_test" SelectCommand="select * from test" ConnectionString="...">
2.使用DataTable为数据源会发现排序,分页包括修改,取消等操作都需要手动实现
<asp:GridView ID="gv_test" runat="server" OnRowCommand="gv_test_RowCommand" OnRowUpdating="gv_test_RowUpdating" OnRowEditing ="gv_test_RowEditing" OnRowCancelingEdit ="gv_test_RowCancelingEdit" OnPageIndexChanging ="gv_test_PageIndexChanging" AllowPaging="True" PageSize="10" AllowSorting="True" >
...
</asp:GridView >
后台:Page_Load: gv_test.SortExpression总是为空,只好将排序字符串储存在新建的属性里gv_test.Attributes.Add("Sort", "lastUpdateDate desc")Protected Sub bind()gv_test.DataSource = getDataTable_bySQL("select * from test order by "+gv_test.Attributes("Sort")) gv_test.DataBind()End Sub DataView比DatatTable功能强大些,可以拿到数据后进行排序。当SQL Server的ntext列不支持order by时候,用DataView可以解决问题,如下:Protected Sub bind()gv_test.DataSource = getDataTable_bySQL("select * from test")Dim dv As DataView = New DataView(getTableData_bySQL("select * from test"))dv.Sort=gv_test.Attributes("Sort")
gv_test.DataSource=dv gv_test.DataBind()End SubProtected Sub gv_test_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles gv_test.Sorting gv_test.EditIndex = -1 If gv_test.Attributes("Sort") = e.SortExpression + " desc" Then gv_test.Attributes("Sort") = e.SortExpression Else gv_test.Attributes("Sort") = e.SortExpression + " desc" End If bind() End Sub Protected Sub gv_test_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) gv_test.PageIndex = e.NewPageIndex gv_test.EditIndex = -1 bind() End Sub Protected Sub gv_test_RowCancelingEdit(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) gv_test.EditIndex = -1 bind() End Sub Protected Sub gv_test_RowUpdating(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gv_test.RowUpdating gv_test.EditIndex = -1 End Sub Public Sub gv_test_RowEditing(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) gv_test.EditIndex = e.NewEditIndex bind() End Sub