2010年6月17日 星期四

GridView 標題排序 來源為 DataTable 換頁

//將撈出的資料儲存至DataTable dt
Protected Sub init_gv()
.............................
.............................
conn.Open()
cmd = New SqlCommand(sqlstr, conn)
dt.Load(cmd.ExecuteReader) //dt為最後撈出的結果
conn.Close()
ViewState("Dt") = dt
Dim dv As New DataView(dt)
dv.Sort = Session("sort_staus")
GridView1.DataSource = dv
GridView1.DataBind()
End Sub

//換頁Sorting不會亂掉
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
GridView1.PageIndex = e.NewPageIndex
Dim dt As DataTable = DirectCast(ViewState("Dt"), DataTable)
Dim dv As New DataView(dt)
dv.Sort = Session("sort_staus")
GridView1.DataSource = dv
GridView1.DataBind()
End Sub
//加入Sorting
Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
Dim dt As DataTable = DirectCast(ViewState("Dt"), DataTable)
Dim dv As New DataView(dt)
If ViewState("Sort").ToString() = " asc" Then
ViewState("Sort") = " desc"
Else
ViewState("Sort") = " asc"
End If
dv.Sort = e.SortExpression + ViewState("Sort").ToString()
Session("sort_staus") = dv.Sort
GridView1.DataSource = dv
ViewState("Dt") = dv.Table
GridView1.DataBind()
End Sub

沒有留言:

張貼留言