How to sort the GridView data in ASP.NET?

Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 108980 red flag
Rating: 4.67 out of 5  
 3 vote(s)

In this article, we shall learn how to sort the GridView data in ASP.NET.


GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well. 

This article is for beginners.

Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.

In this article we are going to learn how to sort the GridView data in ascending or descending order. Let's create a sample page to see how to do this.


<asp:GridView ID="GridView1" OnSorting="SortRecords" runat="server"

AllowSorting="True" CellPadding="4" DataKeyNames="AutoId" />

You may notice that on the .aspx page, we have specified OnSorting event (that fires SortRecords server side methods) and AllowSorting=true to the GridView. This will make the header of the GridView columns as link (In this case we have set AutoGenerateColumns=true to the GridView, so our GridView columns are automatically generated ). In case we are using BoundField or TemplateField, we can use SortExpression property to set the field name to sort on).


string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;



protected void Page_Load(object sender, EventArgs e)


if (!IsPostBack)






protected void SortRecords(object sender, GridViewSortEventArgs e)


string sortExpression = e.SortExpression;

string direction = string.Empty;


if (SortDirection == SortDirection.Ascending)


SortDirection = SortDirection.Descending;

direction = " DESC";




SortDirection = SortDirection.Ascending;

direction = " ASC";


DataTable table = this.GetData();

table.DefaultView.Sort = sortExpression + direction;

GridView1.DataSource = table;





private void BindData()


// specify the data source for the GridView

GridView1.DataSource = this.GetData();

// bind the data now



/// <summary>

/// Gets or sets the grid view sort direction.

/// </summary>

/// <value>

/// The grid view sort direction.

/// </value>

public SortDirection SortDirection




if (ViewState["SortDirection"] == null)


ViewState["SortDirection"] = SortDirection.Ascending;


return (SortDirection)ViewState["SortDirection"];




ViewState["SortDirection"] = value;



private DataTable GetData()


DataTable table = new DataTable();


// get the connection

using (SqlConnection conn = new SqlConnection(_connStr))


// write the sql statement to execute

string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM

PersonalDetail ORDER By AutoId";

// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))


// get the adapter object and attach the command object to it

using (SqlDataAdapter ad = new SqlDataAdapter(cmd))


// fire Fill method to fetch the data and fill into DataTable





return table;


In the above code snippet, first we have populated record to GridView (using BindData method) in the Page_Load event (insider Not IsPostBack, to ensure that the data binding happens only if the request is not a postback request).

When any column of the GridView is clicked, the SortRecords server side method executes that first saves the sort expression and direction (Ascending or Descending order) in the ViewState based on the previous order selected. We have a SortDirection property that saves the current sort direction in the ViewState and based on that the direction is set as ASC or DESC. As the DataSource of this GridView is DataTable so we have used Sort method of its view and set the sort expression. This will sort the rows of the DataTable. After sorting, the GridView data source has been set and the DataBind method has been called. My page output looks below that is sorted by FirstName column.


Hope this article would be useful for the beginners in ASP.NET. Keep reading forthcoming articles and do not forget to refer to our friends.

Thanks and do let me know your comments.

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on | |

Login to vote for this post.

Comments or Responses

Posted by: Loko on: 4/25/2013 | Points: 25
i have a method more simple in few lines: (code in, for translation in c# it is easy)

Dim SortDirection As String, SortExpression As String
SortExpression = e.SortExpression
If (SortExpression = ViewState("SortExpression") And ViewState("SortDirection") = "asc") Then
SortDirection = "desc"
SortDirection = "asc"
End If
ViewState("SortDirection") = SortDirection
ViewState("SortExpression") = SortExpression

Dim dt As Data.DataTable = ds.Tables(0) '<<<< fill ds with a method
dt.DefaultView.Sort = SortExpression & " " & SortDirection

GridView1.DataSource = dt.DefaultView

that's all. it's easy then to place this code in a generic class, to apply to other gridviews

and your method don't manage the case if the user change the sort column.
Posted by: Hornstalk on: 10/18/2013 | Points: 25
The Custom DataGridView Control not only supports data sorting in a single column, but also supports data sorting in multiple columns.

Login to post response

Comment using Facebook(Author doesn't get notification)