vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Tuesday, February 28, 2012

Apply sorting in gridview using asp.net


Introduction:
In this article you have seen about to do sorting in gridview.
Description:
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"
             autogeneratecolumns="False"
       autogenerateselectbutton="false"
       allowpaging="True"
       selectedindex="1"
        AllowSorting ="true"
            runat="server">
         <Columns><asp:TemplateField > <ItemTemplate>
                  <asp:BoundField DataField="Name"
                 HeaderText="Name"
                 InsertVisible="False" ReadOnly="True"
                 SortExpression="Name"    />
             <asp:BoundField DataField="Address"
                 HeaderText="Address"
                 SortExpression="Address" />
                     </Columns></asp:gridview>

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
            GridView1.DataBind()
        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

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

0 comments:

Post a Comment