Home  »  Articles  »  ASP.Net  »

Simple way to Sort Gridview with corresponding Column.

 Posted By : Manoranjan SahooPosted Date : 30/10/2010 07:06:26 AM Category : ASP.Net Points : 8 (Rs 3.00)

Sometimes we need to give the facility of shorting in gridview. So i tried many times and found one simple technique.
Here is the sample code to sort the gridview data on the selection of column header.


CODE :


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    ClientScriptManager cs = Page.ClientScript;
    Type ty = this.GetType();
    try
    {
        DataView dtvv = new DataView();
        DataTable dtpo = new DataTable();
        public static SqlConnection cn=new SqlConnection("Connection string");;
        public SqlCommand cm;
        string CurrentSortColumn = SortColumn;
        SortColumn = e.SortExpression;
        SortDirection direction;
        if (cn.State == ConnectionState.Closed) { cn.Open(); }
        SqlDataReader sdr = null;
        string SQLQuery="select * from databasename";
        cm = new SqlCommand(SQLQuery, cn);
        sdr = cm.ExecuteReader();
        if (sdr != null)
        {
            dtpo.Load(sdr);
            dtvv = new DataView(dtpo);
            if (CurrentSortColumn == SortColumn)
            {
                if (SortAscend == true)
                {
                    dtvv.Sort = "" + SortColumn + " DESC";
                    SortAscend = false;
                }
                else
                {
                    dtvv.Sort = "" + SortColumn + " ASC";
                    SortAscend = true;
                }
            }
            else
            {
                dtvv.Sort = "" + SortColumn + " ASC";
                SortAscend = true;
            }
            GridView1.DataSource = dtvv;
            GridView1.DataBind();
        }
    }
    catch (Exception ex)
    {
    }
}

protected string SortColumn
{
    get
    {
        object o = ViewState["SortColumn"];
        if (o != null)
        {
            return (string)o;
        }
        else/*Default*/
        {
            return "";
        }
    }
    set
    {
        ViewState["SortColumn"] = value;
    }
 }
 protected bool SortAscend
 {
    //SortDirection
    get
    {
        object o = ViewState["SortAscend"];
        if (o != null)
        {
            return (bool)o;
        }
        else/*Default*/
        {
            return true;
        }
    }
    set
    {
        ViewState["SortAscend"] = value;
    }
}


Thank You

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.