If you want to show data to user using Grid View and also wants user to sort data by just clicking header of the Grid view, then this article may be helpful for you. In this article, I will show you the easiest way using which you can enable Sorting in GridView while creating websites. We have to code in such a way that when user clicks on any column header then data in the grid view got sorted according to the data present in that column firstly in increasing order then in decreasing.
- Create a new website or open an existing one in Visual Studio.
- Add a GridView control to one of the pages in the website.
- Select the GridView Control and open its properties. If properties window is not there, then you can open it by hitting shortcut key “Ctrl + W, P” or by going to “View” menu and then “Properties Window”. You can open Properties window just by selecting Grid View then pressing F4.
- Change the value for AllowSorting from False to True. This property is set to False by default.
- Now Open its events window by clicking the lightening icon in the properties window.
- Now double click on the Sorting which will create a new method protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
- Add the following lines of code in that event
DataTable dt = Session["Table"] as DataTable;
if (dt != null)
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = Session["Table"];
- Here we are calling GetSortDirection, which has the information regarding whether the sorting should be done in Ascending order or Descending. Code for that method is as follows
private string GetSortDirection(string column)
string sortDirection = "ASC";
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
if (sortExpression == column)
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
sortDirection = "DESC";
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
Now, you will be having Sorting enabled in your GridView and working fine.
Incoming search terms:
- c# code to sort the data in accending order (1)
- gridview dynamically enable sorting (1)