Sorting in ASP.NET Gridview
I my earlier article we discussed on Paging in Gridview.
No let us see HOW SORTING CAN BE DONE AS WELL.
Please do excuse me this code is also in VB.
But C# Developers don’t worry, an online tool will help
you make the code in C# as well. http://www.developerfusion.com/tools/convert/csharp-to-vb/
We need a SortDirection Property
'//Property For SortDirection
Public Property dir() As SortDirection
Get
If ViewState("dirState") Is Nothing Then
ViewState("dirState") = SortDirection.Ascending
End If
Return DirectCast(ViewState("dirState"), SortDirection)
End Get
Set(ByVal value As SortDirection)
ViewState("dirState") = value
End Set
End PropertyIn the Gridview Allow
Sorting
<asp:GridView ID="GridView1" runat="server" AllowSorting="true">
</asp:GridView>
For Sorting the grid has
an event
Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
If dir = SortDirection.Ascending Then
dir = SortDirection.Descending
strSortingDirection = "Desc"
Else
dir = SortDirection.Ascending
strSortingDirection = "Asc"
End If
Dim sortedView As New DataView(BindData())
sortedView.Sort = Convert.ToString(e.SortExpression) & " " & strSortingDirection
GridView1.DataSource = sortedView
strSortExpression = e.SortExpression
GridView1.DataBind()
End Sub
Now you have sorting
done for all your columns.
If you have Bound Fields
you can add SortExpression set to the Datafield value and thus
those columns will be sort enabled.
Please try out the
effiecient sorting functionality of an asp.net gridview.
Happy Coding J