gridview排序不适用于数字

时间:2009-12-18 07:51:45

标签: c# asp.net gridview sorting

我已经在我的代码隐藏中实现了sort函数,它可以正常使用单词而不是数字... 例如

4,693 
1,494  
23

当我对此进行排序时,我得到了

> 1,494
> 23
> 4,693

所以这意味着它只是检查第一个数字....

我的排序代码是:

 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;
    }

4 个答案:

答案 0 :(得分:3)

数字排序为字符串时会发生这种情况。

它对字符串从左到右进行排序,在你的情况下, 23中的2是在4之前

答案 1 :(得分:3)

如上所述,您是否已将列绑定到字符串以获取这些逗号?

您应该让列绑定到int值,并使用组分隔符将DataFormatString设置为“{0:N}”。 (见BoundField.DataFormatString Property

答案 2 :(得分:2)

看起来它正在将数字排序为字符串 - 即按字母顺序而不是数字顺序排序。我不太清楚你的实际列/值在哪里,你可以用某种类型的转换/转换为整数吗?

答案 3 :(得分:0)

在参考MSDN页面以获得快速教程后,我也遇到了这个问题:https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting(v=vs.110).aspx

您所要做的就是使用第二个参数指定TableData列的类型:

   //To allow sorting numerically, add type param to column
   table1.Columns.Add("GridTest ID", typeof(Int32));

希望这对其他人有帮助。