I decided to write this example because this has been asked many times at the forums. In this article, I will show on how to sort GridView columns manually using a DataTable.
Note that in this example, I used my own database for populating the GridView. See Adding Rows in GridView for more info.
Now to get started lets set up the GridView with TemplateField columns. Since we are working with TemplateFields then we need to handle sorting manually by adding a LinkButton control inside the HeaderTemplate of the TemplateField column.
Note that for the simplicity of this demo, I will show only a single column just for your reference. You can apply the same way mentioned in this example to the other template columns in your GridView that you wan’t to Sort based on your requirements.
Below is the GridView Column mark up:
| <asp:TemplateField> <HeaderTemplate> <asp:LinkButton ID="LinkButtonEmpName" runat="server" Text="Employee Name" CommandName="Sort" CommandArgument="Employees"> </asp:LinkButton> </HeaderTemplate> <ItemTemplate> <asp:Label ID="LabelEmployee" runat="server" Text='<%# Bind("Employees") %>'/> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="TextBoxEmployee" runat="server"/> </FooterTemplate> </asp:TemplateField > |
As you can see I have added a LinkButton under the HeaderTemplate section of the TemplateField and set the CommandName and CommandArgument of the LinkButton.
Since we need to perform sorting manually then we set the value of CommanName to “Sort” so that we can perform certain actions "like sorting" based on that value at RowCommand event later. Also be sure to set the CommandArgument value, the value of the CommandArgument should be the Field Name from your database table that corresponds to a particular column. Like for example in the above declaration, I set the CommandArgument value to “Employees”.
Now let’s proceed to the code behind part of the webform and create the method for binding the GridView. Here are the code blocks below:
| private string GetConnectionString() { //Where DBConnection is the connetion string that was set up in the web config file return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString; } private void BindGridView() { DataTable dt = new DataTable(); SqlConnection connection = new SqlConnection(GetConnectionString()); try { connection.Open(); string sqlStatement = "SELECT * FROM Table1"; SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection); SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); sqlDa.Fill(dt); if (dt.Rows.Count > 0) { DataView dv = dt.DefaultView; if (this.ViewState["SortExpression"] != null) { dv.Sort = string.Format("{0} {1}", ViewState["SortExpression"].ToString(), this.ViewState["SortOrder"].ToString()); } GridViewEmployee.DataSource = dt; GridViewEmployee.DataBind(); } } catch (System.Data.SqlClient.SqlException ex) { string msg = "Fetch Error:"; msg += ex.Message; throw new Exception(msg); } finally { connection.Close(); } } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindGridView(); } } |
For more detail information about Binding the GridView with data then you can refer here: Adding Rows in GridView. Basically what is added in the code above is the sorting functionality using a DataView. Since a LinkButton triggers a postback then we have to maintain the Sort Expression and Sorting Order in the ViewState variables. So if the Sort Expression is available, then the DataView’s Sort property will be set with the ViewState’s SortExpression and SortOrder values.
Now let’s implement the Sorting functionality at RowCommand event. For those who do not know on how to generate the Event in GridView then you can follow these steps below:
Switch to Design View in Visual Studio Designer
- Click on the GridView
- Navigate to the GridView Property Pane and then SWITCH to Event Properties
- From there you would be able to find the RowCommand event
- Double Click on that to generate the Event handler for you
- Then write the codes there
Here’s the code block below for the RowCommand event:
| protected void GridViewEmployee_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("Sort")) { if (ViewState["SortExpression"] != null) { if (this.ViewState["SortExpression"].ToString() == e.CommandArgument.ToString()) { if (ViewState["SortOrder"].ToString() == "ASC") ViewState["SortOrder"] = "DESC"; else ViewState["SortOrder"] = "ASC"; } else { ViewState["SortOrder"] = "ASC"; ViewState["SortExpression"] = e.CommandArgument.ToString(); } } else { ViewState["SortExpression"] = e.CommandArgument.ToString(); ViewState["SortOrder"] = "ASC"; } } //Re Bind The Grid to reflect the Sort Order BindGridView(); } |
Basically, the code above store’s the current Order and Sort Expression in the ViewState. This means that if the column was sorted in ascending order then the new direction has to be descending.
Running the code above will show something like this in the page:
Now clicking on the Employee Name Header will sort the Column like this below:

As you can see the Data in the first column changes the order to descending.
That's it! Hope you will find this example useful!