How to Implement Sorting in GridView in ASP.NET

No.of Views1991
Bookmarked0 times
Downloads 
Votes0
By  Sanjay Verma   On  29 Nov 2010 03:11:02
Tag : ASP.NET , Grid Controls
In this article, i will explain how to implement sorting features to GridView in ASP.NET.i'm using simple idea to implement.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article, i will explain how to implement sorting features to GridView in ASP.NET.i'm using simple idea to implement.

Here i'm going to describes the method and the coding for sorting in Gridview or DataGrid. Sorting in Gridview/DataGrid is required mostly for applications in Asp.Net. The sorting is done by clicking on the columns Headers. And the sorting order can be either ascending or descending.

Implementation

As usual create a simple web project and then drag and drop datagrid within the page.The Datagrid will be as follows with sorting options. Its AllowSorting property is set to true, so that we can sort the data by clicking the column header. Then the column which is bounded to database column should have SortExpression as the name of the column in database table.

Html Code

<asp:DataGrid ID="DataGrid1" runat="server" AllowSorting="true">
<Columns>
      <asp:BoundColumn DataField="FirstName" HeaderText="First Name" SortExpression="FirstName"></asp:BoundColumn>
      <asp:BoundColumn DataField="LastName" HeaderText="Last Name" SortExpression="LastName"></asp:BoundColumn>
      <asp:BoundColumn DataField="City" HeaderText="City" SortExpression="City"></asp:BoundColumn>
      <asp:BoundColumn DataField="BirthDate" HeaderText="Birthdate" SortExpression="Birthdate"></asp:BoundColumn>
</Columns> 
</asp:DataGrid>

Here, there are four fields in Datagrid whose values are coming from database table. And the SortExpression for each BoundColumn contains the real name of the database table's column names which will be passed to the stored procedure to perform the sorting query.Now for Sorting the data, there is one event of the DataGrid for sorting operation called SortCommand.
On the Page_Load event, the Datagrid should be binded as normal way.

I have made a simple function for binding the datagrid and called it in Page_Load event. The Page_Load Event will be like followings.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      If Not IsPostBack Then
               Call BindGrid()
      End If
End Sub

And below is the SortCommand Event. I have used ViewState property to store the values of sorting expression and Sorting order. We can also use static variables(ie. Static string) or hiddenfields for this purpose. When user clicks the column header, this event is called and the values are assinged to the variables. And finally we bind the grid again with sorting orders by calling the BindGrid method at the end of the event.

VB.NET code

Protected Sub dgDetails_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgDetails.SortCommand
            If (ViewState("SortField") <> e.SortExpression) Then
                     ViewState("SortField") = e.SortExpression
                     ViewState("SortOrder") = "1"
            else
                     If (ViewState("SortOrder") = "1") Then
                           ViewState("SortOrder") = "0"
                     Else
                           ViewState("SortOrder") = "1"
              End If
            End If
            Call BindGrid()
End Sub

The BindGrid method is called on Page_Load as well as from the SortCommand Event,

VB.NET code

Sub BindGrid()
         Dim ds As New DataSet
         Dim cmd As New SqlCommand
         Dim con As New SqlConnection

         If ViewState("SortField") = Nothing Then
               ViewState("SortField") = "Name"
         End If

         If ViewState("SortOrder") = Nothing Then
               ViewState("SortOrder") = 1
         End If
         Try
                  cmd.CommandText = "Proc_Employees"
                  cmd.CommandType = CommandType.StoredProcedure
                  cmd.Parameters.Add(New SqlParameter("@mode", "SELECT"))
            cmd.Parameters.Add(New SqlParameter("@sortfield", ViewState("SortField")))
                  cmd.Parameters.Add(New SqlParameter("@sortorder", ViewState("SortOrder")))
                  Dim adp As New SqlDataAdapter
                  cmd.Connection = con
                  con.Open()
                  adp = New SqlDataAdapter(cmd)
                  adp.Fill(ds)

                  DataGrid1.DataSource = ds
                  DataGrid1.DataBind()
         Catch Ex As Exception
                  Throw Ex
         Finally
                  con.Close()
         End Try

End Sub

And following is the Stored Procedure for retrieving the sorted records from the database table. The parameters @sortfield and @sortorder are passed to the stored procedure and then making the whole query with parameters and where clause. The resultant query will return the sorted records from the database table.

Stored Procedure

CREATE PROCEDURE [dbo].[PROC_EMPLOYEES]
(
@mode VARCHAR(20)='select',
@sortfield VARCHAR(20)='',
@sortorder INT=0
)
AS
BEGIN
         DECLARE @STR VARCHAR(2000)
         IF @mode='select'
         BEGIN
               SET @STR = 'Select * from Employees'
               IF @sortfield <> ''
               BEGIN 
                        SET @STR = @STR + ' Order By ' + CONVERT(VARCHAR(20),@sortfield)
                        IF @sortorder = 0
                              SET @STR = @STR + ' Desc'
                        ELSE
                              SET @STR = @STR + ' Asc'
               END

               EXEC(@STR)
         END
END

Conclusion

Through this article, you have learned how to implement sorting features to GridView in ASP.NET.i'm using simple idea to implement.i can say this is a simple practice example for sorting the data in datagrid

 
Sign Up to vote for this article
 
About Author
 
Sanjay Verma
Occupation-Not Provided
Company-Not Provided
Member Type-Fresh
Location-India
Joined date-12 Nov 2010
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top