Monday 20 February 2012

Sorting Grid View In ASP.Net

Sorting Grid View Data In Just One Click On Header ASP.net


GridView control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well. In below sample we are using GridView sorting functionality and sort the columns by just clicking the header name



ASPX Page:


<asp:GridView ID="GridView1" OnSorting="SortRecords" runat="server"

AllowSorting="True" CellPadding="4" DataKeyNames="AutoId" />


You may notice that on the .aspx page, we have specified OnSorting event (that fires SortRecords server side methods) and AllowSorting=true to the GridView. This will make the header of the GridView columns as link (In this case we have set AutoGenerateColumns=true to the GridView, so our GridView columns are automatically generated ). In case we are using BoundField or TemplateField, we can use SortExpression property to set the field name to sort on).



C# Page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Exam_Cell_Default : System.Web.UI.Page
{   
    string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
                if (!IsPostBack)
                {
                BindData();
                }
    }
    protected void SortRecords(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;
        string direction = string.Empty;    
        if (SortDirection == SortDirection.Ascending)
        {
            SortDirection = SortDirection.Descending;
            direction = " DESC";
        }
        else
        {
            SortDirection = SortDirection.Ascending;
            direction = " ASC";
        }
        DataTable table = this.GetData();
        table.DefaultView.Sort = sortExpression + direction;
        GridView1.DataSource = table;
        GridView1.DataBind();
    }

    private void BindData()
    {
    SqlCommand cmd=new SqlCommand...............
    SqlDataAdapter adp=new ........
    DataSet ds=new Dataset;
    adp.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    Session["ssst"]=ds;
    }
   
    public SortDirection SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["SortDirection"];
        }
        set
        {
            ViewState["SortDirection"] = value;
        }
    }
    private DataTable GetData()
    {
       DataTable table = new DataTable();
        DataSet ds = new DataSet();
        ds = (DataSet)Session["ssst"];
        table = ds.Tables[0];
        // fire Fill method to fetch the data and fill into DataTable
        return table;
    }
}



Conclusion:

When any column of the GridView is clicked, the SortRecords server side method executes that first saves the sort expression and direction (Ascending or Descending order) in the ViewState based on the previous order selected. We have a SortDirection property that saves the current sort direction in the ViewState and based on that the direction is set as ASC or DESC. As the DataSource of this GridView is DataTable so we have used Sort method of its view and set the sort expression. This will sort the rows of the DataTable. After sorting, the GridView data source has been set and the DataBind method has been called. My page output looks below that is sorted by FirstName column.

No comments:

Post a Comment

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...