Updated on Kisan Patel
This tutorial will explain you how to implement sorting in ASP.NET gridview?
First we have populated record to GridView using BindData method in the Page_Load event.
Default.aspx
<asp:GridView ID="GridView1" runat="server" />
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } private DataTable GetData() { DataTable table = new DataTable(); // get the connection using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) { // write the sql statement to execute string sql = "SELECT Id, FirstName, LastName, Email, IsActive FROM Students"; // 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 sdt = new SqlDataAdapter(cmd)) { // fire Fill method to fetch the data and fill into DataTable sdt.Fill(table); } } } return table; } private void BindData() { // specify the data source for the GridView GridView1.DataSource = GetData(); // bind the data now GridView1.DataBind(); }
Next, we have specified OnSorting event (that fires SortRecords methods) and AllowSorting=true to the GridView. This will make the header of the GridView columns as link.
<asp:GridView ID="GridView1" OnSorting="SortRecords" runat="server" AllowSorting="True" CellPadding="4" DataKeyNames="Id" />
Next, add the SortRecords Server side event method as shown in below code:
protected void SortRecords(object sender, GridViewSortEventArgs e) { string sortExpression = e.SortExpression; string direction = string.Empty; if (SortDirection == SortDirection.Ascending) { SortDirection = SortDirection.Descending; direction = " DESC"; } else { SortDirection = SortDirection.Ascending; direction = " ASC"; } DataTable table = GetData(); table.DefaultView.Sort = sortExpression + direction; GridView1.DataSource = table; GridView1.DataBind(); } /// <summary> /// Gets or sets the grid view sort direction. /// </summary> /// <value> /// The grid view sort direction. /// </value> public SortDirection SortDirection { get { if (ViewState["SortDirection"] == null) { ViewState["SortDirection"] = SortDirection.Ascending; } return (SortDirection)ViewState["SortDirection"]; } set { ViewState["SortDirection"] = value; } } When any column of the GridView is clicked, the SortRecords server side method fires that first saves the sort expression and direction. 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. The full code of Default.aspc.cs
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; namespace GridViewDemo { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } private DataTable GetData() { DataTable table = new DataTable(); // get the connection using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) { // write the sql statement to execute string sql = "SELECT Id, FirstName, LastName, Email, IsActive FROM Students"; // 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 sdt = new SqlDataAdapter(cmd)) { // fire Fill method to fetch the data and fill into DataTable sdt.Fill(table); } } } return table; } protected void SortRecords(object sender, GridViewSortEventArgs e) { string sortExpression = e.SortExpression; string direction = string.Empty; if (SortDirection == SortDirection.Ascending) { SortDirection = SortDirection.Descending; direction = " DESC"; } else { SortDirection = SortDirection.Ascending; direction = " ASC"; } DataTable table = GetData(); table.DefaultView.Sort = sortExpression + direction; GridView1.DataSource = table; GridView1.DataBind(); } private void BindData() { // specify the data source for the GridView GridView1.DataSource = GetData(); // bind the data now GridView1.DataBind(); } /// <summary> /// Gets or sets the grid view sort direction. /// </summary> /// <value> /// The grid view sort direction. /// </value> public SortDirection SortDirection { get { if (ViewState["SortDirection"] == null) { ViewState["SortDirection"] = SortDirection.Ascending; } return (SortDirection)ViewState["SortDirection"]; } set { ViewState["SortDirection"] = value; } } } }
Demo