welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Tuesday, February 28, 2012

Apply sorting in gridview using

In this article you have seen about to do sorting in gridview.
In a previous article already I discussed about to how to edit and load in gridview and sorting in datatable. For your reference here i mention the previous link...

For doing sorting in gridview you have to do the list of things.
Initially you have to add AllowSorting ="true" in gridview
Add the sort expression in every bound filed or template field in grid view..
Add the below code in GridView1_Sorting event in gridview..

<asp:gridview id="GridView1"
        AllowSorting ="true"
         <Columns><asp:TemplateField > <ItemTemplate>
                  <asp:BoundField DataField="Name"
                 InsertVisible="False" ReadOnly="True"
                 SortExpression="Name"    />
             <asp:BoundField DataField="Address"
                 SortExpression="Address" />

Initially i stored sort expression in viewstate .For an every click its has sorting ascending or descending order

Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
        Dim dt1 As DataTable = GridView1.DataSource
         If dt1.Rows.Count > 0 Then
//Create new dataview instance and pass datatable
            Dim dtview As New DataView(dt1)
  //Sort dataview data based on the sort directin value
           dtview.Sort = e.SortExpression & " " & chksorting(If(ViewState("ord"), "ASC"))
            GridView1.DataSource = dtview
        End If
     End Sub
    Function chksorting(ByRef srt As String) As String
        Dim srtgrid As String
        Select Case srt
//If previous sort direction if ascending order then assign new direction as descending order
            Case "ASC"
                srtgrid = "DESC"
//If previous sort direction if descending order then assign new direction as ascending order
            Case "DESC"
                srtgrid = "ASC"
         End Select
        ViewState("ord") = srtgrid
        Return srtgrid
    End Function

Here you learned do sorting in grdview using dataview.
Post your comments here..Happy coding


Post a Comment