Thursday, September 18, 2008

Adding Sorting image (up down arrow) while sorting grid view asp.net 2.0

This article shows code how to show toggle image according to sort direction while gridview sorting.


//save column name in a view state
Protected Sub gvContentList_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvContentList.Sorting


ViewState.Add("colname", e.SortExpression)


End Sub



Protected Sub gvContentList_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvContentList.RowCreated
Dim defaultsortimage As New Image
defaultsortimage.ImageUrl = "~/images/tbl_ascend_ord.gif"
If e.Row.RowType = DataControlRowType.Header Then
If ViewState("exp") <> "" Then
AddSortImage(e.Row)
Else
e.Row.Cells(0).Controls.Add(defaultsortimage)
End If
End If
End Sub





Public Sub AddSortImage(ByVal headerrow As GridViewRow)
Dim nColumnindex As Integer
Dim sortimage As New Image
Dim sortdirection As String
nColumnindex = getsortcolumnindex(ViewState("colname").ToString())
sortdirection = ViewState("colname").ToString + ".asc"
If ViewState("exp") = sortdirection Then
'sortimage.ImageUrl = "~/images/tbl_ascend_ord.gif"
headerrow.Cells(nColumnindex).CssClass = "sortascheaderstyle"
Else
'sortimage.ImageUrl = "~/images/tbl_descend_ord.gif"
headerrow.Cells(nColumnindex).CssClass = "sortdescheaderstyle"
End If
End Sub


Public Function getsortcolumnindex(ByVal strcol As String)
For Each field As DataControlField In gvContentList.Columns
If field.SortExpression = strcol Then
Return gvContentList.Columns.IndexOf(field)
End If

Next
Return -1
End Function

No comments: