martedì 26 agosto 2008

Paging e Sorting di un GridView

Con questi metodi è possibile gestire il paging e il sorting di un GridView non collegato ad un DataSource.

Private Property GridViewSortDirection() As String
Get
Return IIf(ViewState("SortDirection") = Nothing, "ASC", ViewState("SortDirection"))
End Get
Set(ByVal value As String)
ViewState("SortDirection") = value
End Set
End Property


Private Property GridViewSortExpression() As String
Get
Return IIf(ViewState("SortExpression") = Nothing, String.Empty, ViewState("SortExpression"))
End Get
Set(ByVal value As String)
ViewState("SortExpression") = value
End Set
End Property


Private Function GetSortDirection() As String
Select Case GridViewSortDirection
Case "ASC"
GridViewSortDirection = "DESC"
Case "DESC"
GridViewSortDirection = "ASC"
End Select
Return GridViewSortDirection
End Function


Protected Function SortDataTable(ByVal dataTable As DataTable, ByVal isPageIndexChanging As Boolean) As DataView
If Not dataTable Is Nothing Then
Dim dataView As New DataView(dataTable)
If GridViewSortExpression <> String.Empty Then
If isPageIndexChanging Then
dataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection)
Else
dataView.Sort = String.Format("{0} {1}", GridViewSortExpression, GetSortDirection())
End If
End If
Return dataView
Else
Return New DataView()
End If
End Function

Nell'evento Paging viene passato al SortDataTable il datasource della griglia, che molto probabilmente sarà vuoto. E' conveniente salvare precedentemente il datasource nel viewState e poi passare tale campo al SortDataTable


Protected Sub gridAgenti_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gridAgenti.PageIndexChanging
Try
gridAgenti.DataSource = SortDataTable(gridAgenti.DataSource, True)
gridAgenti.PageIndex = e.NewPageIndex
gridAgenti.DataBind()
Catch ex As Exception
Session.Remove("Exception")
Session.Add("Exception", ex)
Response.Redirect("ErrorPage.aspx")
End Try
End Sub

Protected Sub gridAgenti_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles gridAgenti.Sorting
GridViewSortExpression = e.SortExpression
Dim pageIndex As Integer = gridAgenti.PageIndex
gridAgenti.DataSource = SortDataTable(gridAgenti.DataSource, False)
gridAgenti.DataBind()
gridAgenti.PageIndex = pageIndex
End Sub

Nessun commento: