views:

381

answers:

3

I have implemented the sort function in my codebehind, it works fine with words but not with numbers... eg

4,693 
1,494  
23

when i sort this i get

> 1,494
> 23
> 4,693

so this means its just checking the first number....

my code for sort is:

 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (IsPostBack)
        {
            DataTable dt = Session["TaskTable"] as DataTable;

            if (dt != null)
            {

                //Sort the data.
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                GridView1.DataSource = Session["TaskTable"];
                GridView1.DataBind();
            }
        }
        else
        {
            Response.Redirect("~/Reports1mod.aspx");
        }

    }

    private string GetSortDirection(string column)
    {
        // By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        // Retrieve the last column that was sorted.
        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            // Check if the same column is being sorted.
            // Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        // Save new values in ViewState.
        ViewState["SortDirection"] = sortDirection;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }
A: 

This happens when sorting numbers as strings.

It sorts string left-to-right, which in your case 2 in 23 is before 4.

astander
A: 

It looks like it's sorting the numbers as strings - ie, in alphabetical order rather than numerical order. I can't quite see where your actual column / value is in there, could you surround it with some sort of a cast / convert to an integer?

pete the pagan-gerbil
+1  A: 

As has been said, have you bound the column to a string to get those commas?

You should let the column bind to the int value, and set the DataFormatString to "{0:N}" for numeric with group separator. (See BoundField.DataFormatString Property)

David