使用ADO.NET動態設定GridView資料的排序範例

使用ADO.NET動態設定GridView資料的排序範例

當我們用GirdView搭配DataSouce控制項時,很多的動作在這樣的搭配下都會自動幫我們做,例如GridView的排序功能,只需要在GirdView上設定AllowSorting="True"就能夠自動的有排序的功能。但是如果是沒有用DataSouce,透過ADO.NET給資料的呢??這個範例提供大家參考。

首先設定畫面,畫面中只有安排一個按鈕與一個空的GridView

        <asp:GridView ID="GridView1" runat="server" AllowSorting="True">
        </asp:GridView>

接著,CodeFile的部分範例如下

    Dim ConnStr As String = oConnS.ConnStr

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        '呼叫函數GetData取得資料
        Me.GridView1.DataSource = GetData("", "")
        Me.GridView1.DataBind()
    End Sub

    Protected Function GetData(ByVal SortField As String, ByVal SortDict As String) As DataView
        '取得資料,並傳回DataView
        Using Conn As New SqlConnection(ConnStr)
            Conn.Open()
            Dim SqlTxt As String = ""
            SqlTxt += " SELECT * "
            SqlTxt += " FROM Customers "
            SqlTxt += "  "

            Dim Cmmd As New SqlCommand(SqlTxt, Conn)
            Dim Dt As New DataTable
            Dt.Load(Cmmd.ExecuteReader)

            Dim dv As DataView
            dv = Dt.DefaultView
            If SortField <> "" Then '如果有指定排序的欄位,處理排序
                Dim SortTxt As String
                SortTxt = SortField
                If SortDict = "1" Then
                    SortTxt += " DESC"
                End If
                dv.Sort = SortTxt
            End If

            Return dv

        End Using
    End Function

    Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
        Dim SortField As String = e.SortExpression
        Dim SortDir As String = e.SortDirection

        If ViewState("SortField") IsNot Nothing Then
            If ViewState("SortField") = SortField Then
                SortDir = (CInt(ViewState("SortDir") + 1) Mod 2).ToString
            End If
        End If

        ViewState("SortField") = SortField
        ViewState("SortDir") = SortDir

        Me.GridView1.DataSource = GetData(SortField, SortDir)
        Me.DataBind()
    End Sub

補充說明:

由於動態給予時,當觸發GridView的Sorting時,從e.SortDirection取得的都是固定的0,這導致每次都是由小到大。為了能夠處理第一次點順排,第二次點逆排,第三次點再順排這樣的切換,小喵用ViewState來記錄上次點的狀況,然後用+1後Mod 2的方式來切換0與1

提供大家參考


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat