views:

552

answers:

1

Hi All, I am trying to implement sorting functionality in grid view but its not working.. Code:

//enter code here 
public partial class _Default : System.Web.UI.Page 
{
SqlConnection con;
SqlCommand cmd;
DataSet ds;
SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["myDataSet"] = FillDataSet();

    }
}

private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
    string newSortDirection = String.Empty;

    switch (sortDirection)
    {
        case SortDirection.Ascending:
            newSortDirection = "ASC";
            break;

        case SortDirection.Descending:
            newSortDirection = "DESC";
            break;
    }

    return newSortDirection;
}
protected DataSet FillDataSet()
{
    string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
    con = new SqlConnection(source);
    cmd = new SqlCommand("proc_mygrid", con);
    ds = new DataSet();
    da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();

    return ds;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{

    //DataSet ds = FillDataSet();
    DataTable dt = ((DataSet)Session["myDataSet"]).Tables[0];
    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

Can somebody suggest where I am going wrong?

EDIT:

enter code here  DataTable dtbl = ((DataSet)Session["myDataSet"]).Tables[0];
    dtbl.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
    GridView1.DataSource = dtbl;
    GridView1.DataBind();
A: 

Here is the running code:

  private string GetSortDirection(string column)
{


    string sortDirection = "DESC";


    string sortExpression = ViewState["SortExpression"] as string;

    if (sortExpression != null)
    {

        if (sortExpression == column)
        {
            string lastDirection = ViewState["SortDirection"] as string;
            if ((lastDirection != null) && (lastDirection == "DESC"))
            {
                sortDirection = "ASC";
            }
        }
    }


    ViewState["SortDirection"] = sortDirection;
    ViewState["SortExpression"] = column;

    return sortDirection;
}

 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{

    DataTable dtbl = ((DataSet)Session["myDataSet"]).Tables[0];
    dtbl.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
    GridView1.DataSource = dtbl;
    GridView1.DataBind();

}

Wondering