GridView Paging and Sorting in ASP.NET without using a DataSource

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

Download Source Code

Introduction:

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

Step 1:

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

Step 2:

Write following in page load event

protected void Page_Load(object sender, EventArgs e)
{
     if (!IsPostBack)
     {
          BindGridView();
     }
}

BindGridView() method populates data in the GridView

Step 3:

Write following method in 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 DataSet using “ds.Tables[0].DefaultView”. DataView.Sort property is used to sort data of in the DataView. DataView.Sort property takes value as Column name followed by ASC or DESC like “EmployeeID ASC/DESC” format. It is set by two ViewState values “SortExpression” and “SortDirection” that are set in GridView2_Sorting event. If “SortDirection” is not found in ViewState, it is by default set to “ASC”. Finally sorted DataView is set as DataSource of the GridView and DataBind() method is called to bind data to the GridView.

Step 4:

Set 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 other style). On clicking on a page number, data of respective page is displayed in the GridView. After setting AllowSorting to true, GridView column headers are turned into LinkButtons. Clicking on these LinkButtons will sort the GridView according to their columns. In the property window of GridView select Events tab to display events of the GridView and double click on PageIndexChanging and Sorting  events to generate structure of these events. Write following codes in these events

protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
     GridView2.PageIndex = e.NewPageIndex;
     BindGridView();
}

PageIndexChanging event is fired before changing the current page index of GridView. GridView2.PageIndex is set to the new page index using GridViewPageEventArgs.NewPageIndex. Then 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();
}

Sorting eveng is fired before GridView is sorted. We have to store SortDirection (Ascending or Descending) in ViewState because on sorting, page is posted back to the server and to remmember last SortDirection we have to maintain its state. If GridView is sorted for the first time or sorting is being done on a new column, sorting direction will be Ascending so ViewState is set to “ASC”. GridView2.PageIndex is set to 0 to display data from 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 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:

string sortDirection = “”, sortExpression = “”;

9 thoughts on “GridView Paging and Sorting in ASP.NET without using a DataSource

  1. Shikha

    after compilation i have two errors
    unassigned variable constring.
    unassigned variable sortDirection.
    i.e line no 7 and 24 in your bindgrid code..

    plz help me soon with solution..

    thnx

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *