Protected Sub Gridv_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles Gridv.Sorting
Dim sortExpression As String = e.SortExpression
ViewState("SortExpression") = sortExpression
If SortDirection = SortDirection.Ascending Then
SortDirection = SortDirection.Descending
SortGridView(sortExpression, DESCENDING)
Else
SortDirection = SortDirection.Ascending
SortGridView(sortExpression, ASCENDING)
End If
End Sub
Private Property SortDirection() As SortDirection
Get
If ViewState("sortDirection") Is Nothing Then
ViewState("sortDirection") = SortDirection.Ascending
End If
Return DirectCast(ViewState("sortDirection"), SortDirection)
End Get
Set(ByVal value As SortDirection)
ViewState("sortDirection") = value
End Set
End Property
Private Sub SortGridView(ByVal sortExpression As String, ByVal direction As String)
Dim con As OleDbConnection = Nothing
Try
con = New OleDbConnection(";Extended Properties=""Excel 8.0"";")
Catch ex As Exception
lt1.Text = ex.Message
Exit Sub
End Try
Dim sSQL As String = "SELECT * FROM [Excel$];"
Dim cmd As New OleDbDataAdapter(sSQL, con)
Dim ds As New DataSet
Try
cmd.Fill(ds, sSQL)
Dim dv As DataView = New DataView(ds.Tables("sSQL"))
Gridv.DataSource = ds
Gridv.DataBind()
Catch ex As Exception
lt1.Text = ex.Message
Exit Sub
Finally
con.Close()
End Try
End Sub
Protected Sub Gridv_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Header Then
Dim sortColumnIndex As Integer = GetSortColumnIndex()
If sortColumnIndex <> -1 Then
AddSortImage(sortColumnIndex, e.Row)
End If
End If
End Sub
Private Function GetSortColumnIndex() As Integer
For Each field As DataControlField In Gridv.Columns
If field.SortExpression = DirectCast(ViewState("SortExpression"), String) Then
Return Gridv.Columns.IndexOf(field)
End If
Next
Return -1
End Function
Private Sub AddSortImage(ByVal columnIndex As Integer, ByVal headerRow As GridViewRow)
Dim sortImage As New Image()
If SortDirection = SortDirection.Ascending Then
sortImage.ImageUrl = "images/arrow.gif"
sortImage.AlternateText = "Ascending Order"
Else
sortImage.ImageUrl = "images/arrowdown.gif"
sortImage.AlternateText = "Descending Order"
End If
headerRow.Cells(columnIndex).Controls.Add(sortImage)
End Sub