【问题标题】:gridview sort not working for numbersgridview 排序不适用于数字
【发布时间】:2010-12-27 23:14:19
【问题描述】:

我已经在我的代码隐藏中实现了排序功能,它适用于单词但不适用于数字...... 例如

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

【问题讨论】:

  • 这可能是因为表格包含字符串,而不是整数。
  • 您是如何填充该字段的...您是否使用数据格式字符串填充为数字,或者您将数字转换为字符串以添加逗号,然后填充网格视图列?

标签: c# asp.net gridview sorting


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        在参考 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));
        

        希望这对其他人有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-07-10
          • 1970-01-01
          • 1970-01-01
          • 2016-03-23
          • 2016-08-04
          • 2015-01-28
          • 1970-01-01
          相关资源
          最近更新 更多