How to sort the GridView data

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

In this article, we shall see how to sort columns data in the GridView.


GridView control has a property called "AllowSorting" which enables us to sort the GridView records. So to enable sorting for GridView, set AllowSorting property of the GridView to true and you will need to also handle the OnSorting event. Setting AllowSorting to true converts the column headers to a clickable link and clicking those headers fires the OnSorting event.

To get hundreds of .NET How to’s like this, click here.

The following code snippet from ASPX page shows how these properties and events are set.

ASPX Page:

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

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

CODE Behind:

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 records to the GridView (using BindData method) in the Page_Load event (inside Not IsPostBack, to ensure that data binding happens only if the request is not a postback request).

You may notice that on the .aspx page, we have specified OnSorting event (that fires SortRecords methods) and AllowSorting=true to the GridView. 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.

When any column of the GridView is clicked, the SortRecords server side method fires that first saves the sort expression and direction (Ascending or Descending order) into the string variable. We have a SortDirection property that saves the current sort direction in the ViewState and based on that the direction string variable 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.

Now when we run this page, we get the output as shown below.


Setting AllowSorting=true and handling the OnSorting event, we can sort the records of the GridView.
Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: IT Funda
Member Level: Starter
Member Status: Member
Member Since: 5/21/2011 3:32:40 AM
Country: India
Thanks Regards
Get .NET How to | jQuery How to.

Login to vote for this post.

Comments or Responses

Posted by: Susanthampy on: 5/27/2011 | Points: 25
Posted by: Prabhakar on: 5/27/2011 | Points: 25
Gud one . . NIce Tricks working with Database . .

Posted by: Nileshdhorajiya on: 12/15/2011 | Points: 25
It's really helpful work done
Thanks for posting such a nice article
It is working absolutly fine
Posted by: Netgrid on: 10/30/2012 | Points: 25
data sorting information is contained in grid headers. Users may set single or multiple sorting in one or multiple headers. On programming level, sorting looks as follows:

//Get top-level header
Header header = grid.Headers[0];

header["Product"].SortDirection = SortDirection.Ascending;
header["Price"].SortDirection = SortDirection.Descending;
you can also try dapfor. com

Login to post response

Comment using Facebook(Author doesn't get notification)