Sorting in gridview is not working

17,959

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 dt = ((DataSet)Session["myDataSet"]).Tables[0];
   dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
   GridView1.DataSource = dt;
   GridView1.DataBind();
}
Share:
17,959
Leon Lang
Author by

Leon Lang

:-)

Updated on June 07, 2022

Comments

  • Leon Lang
    Leon Lang almost 2 years

    I am trying Sorting functionality in Grid view but its not working.Can some body help?

    Code:

      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)
    {
        DataTable dt = GridView1.DataSource as DataTable;
        if (dt != null)
        {
            DataView dv = new DataView(dt);
            dv.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
            GridView1.DataSource = dv;
            GridView1.DataBind();
       }
    

    Here dt is coming null.why? pls help thanks.

    EDIT:

    enter code here  <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" 
        GridLines="None" AllowPaging="true" AllowSorting="true" PageSize="12" 
        onpageindexchanging="GridView1_PageIndexChanging" 
        onsorting="GridView1_Sorting">
    

    EDIT(Total code)

    public partial class _Default : System.Web.UI.Page 
    {
        SqlConnection con;
        SqlCommand cmd;
        DataSet ds;
        SqlDataAdapter da;
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        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 GetValues(object sender, EventArgs e)
        {
            FillDataSet();
        }
    
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
           int newPagenumber = e.NewPageIndex;
           GridView1.PageIndex = newPagenumber;
           GridView1.DataSource = FillDataSet();
           GridView1.DataBind();
    
        }
    
    
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
    
            DataSet ds = FillDataSet();
            DataTable dt = ds.Tables[0];
            if (dt != null)
            {
                dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
    
  • Leon Lang
    Leon Lang over 14 years
    Tried and changed the code to DataSet ds = FillDataSet(); DataTable dt = ds.Tables[0]; if (dt != null) {......} Now dv.Sort is having value "Id ASc"[Id name of a col]..but still the sorting is not working :-(
  • JohnIdol
    JohnIdol over 14 years
    just go: dt.DefaultView.Sort = "ID ASC";
  • Leon Lang
    Leon Lang over 14 years
    Not working..updated code: DataSet ds = FillDataSet(); DataTable dt = ds.Tables[0]; if (dt != null) { DataView dv = new DataView(dt); dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); //dv.Sort = e.SortExpression +" "+ ConvertSortDirectionToSql(e.SortDirection); GridView1.DataSource = dv; GridView1.DataBind(); } any clue?
  • JohnIdol
    JohnIdol over 14 years
    yes instead of creating a new DataView (dv) just go: dt.DefaultView.Sort = "ID ASC"; as in my previous comment and then just call GridView1.DataBind();
  • JohnIdol
    JohnIdol over 14 years
    you don't need to reassign the datasource you just need to sort the default view of the current datasource (in your case the datatable dt)
  • Leon Lang
    Leon Lang over 14 years
    Getting a bit confused..can u pls code it. Do un want some thing like: if (dt != null) { dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); GridView1.DataBind(); }
  • Leon Lang
    Leon Lang over 14 years
    Thanks for all ur help but it didnt work :-(. No I have only one table.also edited the post for Gridview? pls look at it..Am I missing something there?
  • JohnIdol
    JohnIdol over 14 years
    try resetting dt as datasource right before GridView1.DataBind();
  • Leon Lang
    Leon Lang over 14 years
    already tried but didnt work..here are some findings, I have 3 cols..Id,Fname and Lname.when i click on Id nothing happens but when I click on Fname the first(only first) row gets sorted.rest of teh rows doesnt change..
  • JohnIdol
    JohnIdol over 14 years
    are you databinding somewhere else? maybe you are overriding the sorting. Is FillDataSet called every pageload or where?
  • Leon Lang
    Leon Lang over 14 years
    FillDataSet is a separate method for filling the dataset.code is already there in original post.I am calling this method from Sorting method.For every sorting this will b called.
  • JohnIdol
    JohnIdol over 14 years
    yes - but the sorting causes triggers a postback causing the whole page to reload. I'd say put breakpoints in your code every time you do a DataBind() on the grid and see if the one in the sorting method is the last one to fire. If not that's the reason why it doesn't work. If it's the last then again we're missing smt else :)
  • JohnIdol
    JohnIdol over 14 years
    can you please show your pageLoad? are you doing something like this in it? if (!IsPostBack){ FillDataSet();}
  • JohnIdol
    JohnIdol over 14 years
    have a look at this link - code is pretty similar except that he's storing the dataview in session and using it as datasource --> knowdotnet.com/articles/sortingaspgrid.html . As an alternative - this guy is reloading the data when he needs to sort (which I do not advice but it's another alternative) --> dotnetjohn.com/articles.aspx?articleid=53 .
  • Leon Lang
    Leon Lang over 14 years
    Finally its working. I have updated the code.Thaks a lot for all ur help..It was really a long Comment chain. :-) :-)
  • LFish
    LFish over 10 years
    Could you provide some explanation both to the problem and to your code please? Your code might seem obvious to some but also might not be like for me at the moment.