Please disable your adblock and script blockers to view this page
 

Sorting in Asp.Net GridView by column header in ascending descending order

Introduction: In this article i am going to explain How to implement or enable sorting in asp.net GridView records in ascending or descending order by clicking on GridView's column header in Asp.net both using C# and VB language. In previous article i explained How to Bind and implement search gridview records and Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView and WCF Service to bind,insert,edit,update,delete and Highlight gridview row on mouse over using CSS and Bind,upload,download,delete image files from the GridView and Display Serial Number automatically in GridView.

Sorting in asp.net GridView

Description: To enable sorting in GridView we need to set the AllowSorting property to true and SortExpression property as highlighted in yellow color in this article. After setting these properties the Columns in Gridview's header will turn into clickable links. Clicking on Header columns sorts the grid view records in ascending or descending order. We need to code to handle the sort direction and accordingly performing sorting. We will use ViewState to save the ascending or descending direction.

Implementation: Let's create an asp.net application to check the sorting in action.

First of all create a DataBase in Sql server e.g." Books_DB" and create "BookDetails"  table using the script below:

CREATE TABLE [dbo].[BookDetails]
(
                [ID] [int] IDENTITY(1,1) NOT NULL,
                [BookName] [nvarchar](max) NULL,
                [Author] [nvarchar](max) NULL,
                [Publisher] [nvarchar](max) NULL,
                [Price] [decimal](18, 2) NOT NULL
)
  • Add some records in the table
  • Then in the web.config file create the connection string in <configuration> tag as:
 <connectionStrings>
    <add name="conStr" connectionString="Data Source=lalit;Initial Catalog=Books_DB;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source and Initial catalog as per your application.
  •  In the <body> tag of design page (.aspx) place a GridView control and configure it as:
 HTML Source
<div>
    <fieldset style="width:310px;">
    <legend>Soring in Asp.net Gridview</legend>   
    <asp:GridView ID="grdBookDetails" runat="server"
              AutoGenerateColumns="False" AllowSorting="true"
            onsorting="grdBookDetails_Sorting">          
<Columns>
<asp:TemplateField HeaderText="Book Name" SortExpression="BookName">
<ItemTemplate>
    <asp:Label ID="lblBookName" Text='<%#Eval("BookName")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
    <asp:TemplateField HeaderText="Author" SortExpression="Author">
<ItemTemplate>
    <asp:Label ID="lblAuthor" Text='<%#Eval("Author")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
    <asp:TemplateField HeaderText="Publisher" SortExpression="Publisher">
<ItemTemplate>
    <asp:Label ID="lblPublisher" Text='<%#Eval("Publisher")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="Price">
<ItemTemplate>
    <asp:Label ID="lblPrice" Text='<%#Eval("Price")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</fieldset>
    </div>

C#.Net code to implement sorting in GridView
  • In the code behind file (.aspx.cs) first include the following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

then write the code as:

DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
         if (!Page.IsPostBack)
        {
            ViewState["sortOrder"] = "";
            BindGridView("", "");
        }
    }

    private void BindGridView(string sortExp, string sortDir)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select * from BookDetails", con);
      
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            DataView dv = new DataView();
            dv = dt.DefaultView;

            if (sortExp != string.Empty)
            {
                dv.Sort = string.Format("{0} {1}", sortExp, sortDir);
            }        
     
            grdBookDetails.DataSource = dv;
            grdBookDetails.DataBind();
        }
    }

    public string sortOrder
    {
        get
        {
            if (ViewState["sortOrder"].ToString() == "desc")
            {
                ViewState["sortOrder"] = "asc";
            }
            else
            {
                ViewState["sortOrder"] = "desc";
            }

            return ViewState["sortOrder"].ToString();
        }
        set
        {
            ViewState["sortOrder"] = value;
        }
    }

    protected void grdBookDetails_Sorting(object sender, GridViewSortEventArgs e)
    {
        BindGridView(e.SortExpression, sortOrder);
    }   

VB.Net code to implement sorting in GridView
  • Design the page as shown in HTML Source as mentioned above but remove onsorting="grdBookDetails_Sorting" from the GridView source code.
  • Then in code behind file(.aspx.vb) first include the following namespaces :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Then write the code as:

Dim dt As New DataTable
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            ViewState("sortOrder") = ""
            BindGridView("", "")
        End If
    End Sub

    Private Sub BindGridView(sortExp As String, sortDir As String)
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
        Dim cmd As New SqlCommand("select * from BookDetails", con)

        Dim adp As New SqlDataAdapter(cmd)
        adp.Fill(dt)
        If dt.Rows.Count > 0 Then
            Dim dv As New DataView()
            dv = dt.DefaultView
            If sortExp <> String.Empty Then
                dv.Sort = String.Format("{0} {1}", sortExp, sortDir)
            End If
            grdBookDetails.DataSource = dv
            grdBookDetails.DataBind()
        End If
    End Sub

    Public Property sortOrder() As String
        Get
            If ViewState("sortOrder").ToString() = "desc" Then
                ViewState("sortOrder") = "asc"
            Else
                ViewState("sortOrder") = "desc"
            End If

            Return ViewState("sortOrder").ToString()
        End Get
        Set(value As String)
            ViewState("sortOrder") = value
        End Set
    End Property

    Protected Sub grdBookDetails_Sorting(sender As Object, e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdBookDetails.Sorting
        BindGridView(e.SortExpression, sortOrder)
    End Sub

Now over to you:
" I hope you have got the way to sort the records in gridview and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

4 comments

Click here for comments
Intel
admin
February 23, 2014 ×

Nice Post Sir ....

Reply
avatar
February 23, 2014 ×

Thanks a lot for your feedback..stay connected and keep reading for more useful updates like this..:)

Reply
avatar
Anonymous
admin
March 11, 2014 ×

Thanks! It helped me nicely.

Reply
avatar
March 14, 2014 ×

Hello ..i am glad you found this article helpful..stay connected and keep reading..:)

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon