GridView Paging and Sorting in ASP.NET Without Using a DataSource


Introduction

In this article I will explain how to enable paging and sorting in a GridView control manually without using a DataSource, like a SqlDataSource.

Step 1

Create a new ASP.NET Web Application and drag a GridView control to a Default.aspx in design view.

Step 2

Write the following in the page load event:

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        BindGridView();

    }

}

The BindGridView() method populates the data in the GridView.

Step 3

Write the following method in the Default.aspx.cs file:

private void BindGridView()

{

    SqlConnection con;

    DataSet ds;

    string ConString, CmdString;

 

    ConString = System.Configuration.ConfigurationManager.ConnectionStrings["PagingConnectionString"].ConnectionString;

    con = new SqlConnection(ConString);

    string sortDirection, sortExpression;

   

    CmdString = "SELECT TOP (100) EmployeeID, LastName, FirstName, DepartmentID, Salary, HireDate FROM Employees";

    ds = new DataSet();

    using (SqlDataAdapter sda = new SqlDataAdapter(CmdString, con))

    {

        sda.Fill(ds);

        if (ds.Tables.Count > 0)

        {

            DataView dv = ds.Tables[0].DefaultView;

            if (ViewState["SortDirection"] != null)

            {

                sortDirection = ViewState["SortDirection"].ToString();

            }

 

            if (ViewState["SortExpression"] != null)

            {

                sortExpression = ViewState["SortExpression"].ToString();

                dv.Sort = string.Concat(sortExpression, " ", sortDirection);

            }

            GridView2.DataSource = dv;

            GridView2.DataBind();

        }

    }  

}

Here, first a SqlDataAdapter is used to fill data in a DataSet then a DataView is initialised from the DataSet using "ds.Tables[0].DefaultView". The DataView.Sort property is used to sort data in the DataView. The DataView.Sort property takes Column name as a value followed by "ASC" or "DESC" like "EmployeeID ASC/DESC" format. It is set by the two ViewState values "SortExpression" and "SortDirection" that are set in the GridView2_Sorting event. If "SortDirection" is not found in ViewState, it is by default set to "ASC". Finally, the sorted DataView is set as a DataSource of the GridView and the DataBind() method is called to bind data to the GridView.

Step 4

Set the AllowPaging and AllowSorting property of the GridView to true. After setting AllowPaging to true, a Paging bar is added to the bottom of the GridView. This paging bar contains page numbers (this can be formatted to another style). On clicking on a page number, the data of the respective page is displayed in the GridView. After setting AllowSorting to true, the GridView column headers are turned into LinkButtons. Clicking on these LinkButtons will sort the GridView by their columns. In the property window of the GridView select the Events tab to the display events of the GridView and double-click on the PageIndexChanging and Sorting events to generate the methods for these events. Use the following code in these events:

protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

    GridView2.PageIndex = e.NewPageIndex;

    BindGridView();

}

The PageIndexChanging event is fired before changing the current page index of the GridView. GridView2.PageIndex is set to the new page index using GridViewPageEventArgs.NewPageIndex. Then the BindGridView() method is called to bind data to the GridView again.

protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)

{

    if (ViewState["SortDirection"] == null|| ViewState["SortExpression"].ToString()!=e.SortExpression)

    {

        ViewState["SortDirection"] = "ASC";

        GridView2.PageIndex = 0;

    }

    else if (ViewState["SortDirection"].ToString() =="ASC")

    {

        ViewState["SortDirection"] = "DESC";

    }

    else if (ViewState["SortDirection"].ToString() =="DESC")

    {

        ViewState["SortDirection"] = "ASC";

    }

 

    ViewState["SortExpression"] = e.SortExpression;

 

    BindGridView();

}

The Sorting eveng is fired before the GridView is sorted. We have to store the SortDirection (Ascending or Descending) in the ViewState because on sorting, the page is posted back to the server and to remmember the last SortDirection we have to maintain its state. If the GridView is sorted for the first time or sorting is being done on a new column then the sorting direction will be Ascending so the ViewState is set to "ASC". GridView2.PageIndex is set to 0 to display data from the first page when a new column is being sorted. Othewise when the same column is clicked for sorting more than once, its SortDirection value is toggled. When SortDirection is "ASC" it is set to "DESC" else if it is "ASC" it is set to "DESC". At last the BindGridView() method is called to load data with new sorting.

Step 5

Format the GridView using Auto Format. At the bottom of the GridView property window, click on the Auto Format link. This will open some predefined schemes for the GridView. Click on a scheme on the left pane and click on ok to apply. I choose Rainy Day.

Output

GridView-Paging-and-Sorting-in-ASP.NET.jpg