gridview排序不适用于数字

我已经在我的代码隐藏中实现了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; } 

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

您应该让列绑定到int值,并将DataFormatString设置为带有组分隔符的数字的“{0:N}”。 (请参阅BoundField.DataFormatString属性 )

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

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

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

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

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

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

希望这对其他人有帮助。