GridView用資料來源控制元件和用DataTable作為資料來源的不同

白馬酒涼發表於2013-07-04

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 Sub
    Protected Sub gv_test_Sorting(ByVal sender As ObjectByVal e As GridViewSortEventArgsHandles 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 ObjectByVal e As GridViewPageEventArgs)
        gv_test.PageIndex = e.NewPageIndex
        gv_test.EditIndex = -1
        bind()
    End Sub
    Protected Sub gv_test_RowCancelingEdit(ByVal sender As System.ObjectByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)
        gv_test.EditIndex = -1
        bind()
    End Sub
    Protected Sub gv_test_RowUpdating(ByVal sender As System.ObjectByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgsHandles gv_test.RowUpdating
        gv_test.EditIndex = -1
    End Sub
    Public Sub gv_test_RowEditing(ByVal sender As System.ObjectByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
        gv_test.EditIndex = e.NewEditIndex
        bind()
    End Sub
 
 

 

相關文章