In this article I will explain with an example, how to implement Sorting in TemplateField column using SortExpression property in ASP.Net GridView using C# and VB.Net.
The Columns Header are made clickable and when the Column Headers are clicked, the records are sorted in Ascending or Descending order in GridView.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net GridView with one TemplateField column and three BoundField columns. In order to implement Paging in GridView, AllowPaging property is set to true and OnPageIndexChanging event has been assigned.
For implementing Sorting, AllowSorting property is set to true and OnSorting event has been assigned.
Also for each TemplateField and BoundField column, the SortExpression property is set to the value of Column field.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true" OnSorting="OnSorting" OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
    <Columns>
        <asp:TemplateField ItemStyle-Width="150px" HeaderText="Customer ID" SortExpression="CustomerID">
            <ItemTemplate>
                <%# Eval("CustomerID")%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" SortExpression="ContactName" />
        <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
        <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
    </Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
 
 
Populating GridView from database
Inside the Page Load event of the page, the GridView is populated with records from the Customers table of the Northwind database.
The SortDirection property is a ViewState property which is used to save the Sort Direction of GridView during PostBacks.
Once the DataTable is populated, it is converted into a DataView and then the SortExpression and SortDirection values are used to sort the data.
C#
private string SortDirection
{
    get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
    set { ViewState["SortDirection"] = value; }
}
 
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid(string sortExpression = null)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    if (sortExpression != null)
                    {
                        DataView dv = dt.AsDataView();
                        this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
 
                        dv.Sort = sortExpression + " " + this.SortDirection;
                        GridView1.DataSource = dv;
                    }
                    else
                    {
                        GridView1.DataSource = dt;
                    }
                    GridView1.DataBind();
                }
            }
        }
    }
}
 
VB.Net
Private Property SortDirection As String
    Get
        Return IIf(ViewState("SortDirection") IsNot Nothing, Convert.ToString(ViewState("SortDirection")), "ASC")
    End Get
    Set(value As String)
        ViewState("SortDirection") = value
    End Set
End Property
 
 
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid(Optional ByVal sortExpression As String = Nothing)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers")
    Dim sda As SqlDataAdapter = New SqlDataAdapter
    cmd.Connection = con
    sda.SelectCommand = cmd
    Dim dt As DataTable = New DataTable
    sda.Fill(dt)
    If (Not (sortExpression) Is Nothing) Then
        Dim dv As DataView = dt.AsDataView
        Me.SortDirection = IIf(Me.SortDirection = "ASC", "DESC", "ASC")
        dv.Sort = sortExpression & " " & Me.SortDirection
        GridView1.DataSource = dv
    Else
        GridView1.DataSource = dt
    End If
 
    GridView1.DataBind()
End Sub
 
 
Implementing Paging in GridView
The following event handler is executed when a page is changed inside the GridView.
The value of the PageIndex of the Page which was clicked is present inside the NewPageIndex property of the GridViewPageEventArgs object and it is set to the PageIndex property of the GridView and the GridView is again populated by calling the BindGrid function.
C#
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
    GridView1.PageIndex = e.NewPageIndex
    Me.BindGrid()
End Sub
 
 
Implementing Sorting in GridView using SortExpression
The following event handler is executed when a Column is sorted in GridView.
The value of the Sort Expression of the Column which was clicked is present inside the SortExpression property of the GridViewSortEventArgs object and it is passed as parameter to the BindGrid function.
C#
protected void OnSorting(object sender, GridViewSortEventArgs e)
{
    this.BindGrid(e.SortExpression);
}
 
VB.Net
Protected Sub OnSorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
    Me.BindGrid(e.SortExpression)
End Sub
 
 
Screenshot
Sorting in TemplateField column using SortExpression in ASP.Net GridView
 
 
Demo
 
 
Downloads