Paging and Sorting in ASP.NET GridView
The ASP.NET GridView control is used to display the values of a data source in a table. ASP.NET provides the sorting feature in a GridView Control. The records displayed in a GridView control can be sorted in ascending or descending order.
In this article I will explain how to do paging and sorting in ASP.NET GridView.
The following is the step-by-step explanation.
Step1: Create a table in the database.
- CREATE TABLE [dbo].[Teacher](
- [TeacherId] [int] NULL,
- [FirstName] [varchar](50) NULL,
- [LastName] [varchar](50) NULL,
- [Status] [varchar](50) NULL,
- [Nationality] [varchar](50) NULL,
- [Grade] [nchar](10) NULL
- ) ON [PRIMARY]
Step 2: Create a new ASP.NET web application and drag a GridView control in the Default.aspx design view. Set the property AllowSorting="true".
Step 3: Write the following in the page load event:
- if (!Page.IsPostBack)
- {
- gvTeacher.DataSource = BindGridView();
- gvTeacher.DataBind();
- }
Step 4: The BindGridView() method populates the data in the GridView. Write the following method in the Default.aspx.cs file:
- protected void gvTeacher_Sorting(object sender, GridViewSortEventArgs e)
- {
- string sortingDirection = string.Empty;
- if (direction == SortDirection.Ascending)
- {
- direction = SortDirection.Descending;
- sortingDirection = "Desc";
-
- }
- else
- {
- direction = SortDirection.Ascending;
- sortingDirection = "Asc";
-
- }
- DataView sortedView = new DataView(BindGridView());
- sortedView.Sort = e.SortExpression + " " + sortingDirection;
- Session["SortedView"] = sortedView;
- gvTeacher.DataSource = sortedView;
- gvTeacher.DataBind();
- }
Note: GridViewSortEventArgs is used to perform GridView sorting. There are two properties.
SortDirection specifies the direction to sort the GridView column, either by ascending or descending order.
Step 5: Select the GridView and double-click on PageIndexChanging .Write the following code:
- protected void gvTeacher_PageIndexChanging(object sender, GridViewPageEventArgs e)
- {
- gvTeacher.PageIndex = e.NewPageIndex;
- if (Session["SortedView"] != null)
- {
- gvTeacher.DataSource = Session["SortedView"];
- gvTeacher.DataBind();
- }
- else
- {
- gvTeacher.DataSource = BindGridView();
- gvTeacher.DataBind();
- }
- }
Step 6: Now maintain the SortDirection (Ascending or Descending) in ViewState by adding the following code.
- public SortDirection direction
- {
- get
- {
- if (ViewState["directionState"] == null)
- {
- ViewState["directionState"] = SortDirection.Ascending;
- }
- return (SortDirection)ViewState["directionState"];
- }
- set
- {
- ViewState["directionState"] = value;
- }
- }
Step 7: The First Name is in ascending order as in the following:
The First Name in descending order as in the following: