关于 DataGridView 排序的 C# 问题

标签 c# sorting datagridview

我有两个问题:

  1. 有没有办法按列对 DataGridView 进行排序 - 我想使用代码来执行此操作,以便我的方法之一可以对 DataGridView 进行排序。 (与用户点击列标题相同的效果,但没有点击。)

  2. 当我对具有decimal 值(double 类型)的列进行排序时,排序认为 9.99 大于 24.99 - 有什么方法可以防止这种情况发生排序行为的类型?

更新:由于评论中的链接,问题 1 已解决。 我还找到了问题 2 的问题原因:我的专栏中的值为 (double)price + "€"。我尝试删除 + "€" 并开始按我想要的方式排序。 现在我希望它能够排序,同时以某种方式保留 €。

最佳答案

由于 stuartd 正确地回答了第一个问题,我们将重点关注第二个问题:

When I sort a column with decimal values (of type double) the sorting believes that 9.99 is larger than 24.99 - is there any way to prevent this type of sorting behaviour?

正如您所注意到的,删除 + "€" 更正了您的问题,因为使用它该列执行的是 string 比较,而不是预期的 double 比较。您可以使用 CultureInfo 修复此问题将该列格式化为货币列。

CultureInfo ci = new CultureInfo("fr-FR");
this.dataGridView1.Columns[0].DefaultCellStyle.FormatProvider = ci.NumberFormat;
this.dataGridView1.Columns[0].DefaultCellStyle.Format = "c";

unsorted list sort asc sort desc

关于关于 DataGridView 排序的 C# 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768938/

相关文章:

java - java中的自定义字符串排序

r - 如何对矩阵的条形图进行排序?

C# DataGridView,大单元格 : Content never fully visible, 滚动跳过单元格

c# - Winform 数据绑定(bind)

c# - 如何删除选中复选框的数据 GridView 中的行?

c# - SQL Server datetime 和 datetimeoffset 的等效 C# 数据类型是什么?

c# - 将图像从 GIF 转换为 JPEG

c# - HttpClient在c#中将Host和UserAgent添加到请求中

c# - 使用 .Net 如何使用 Sort 方法对数组进行反向排序,即从 Z 到 A?

c# - XmlWriter 异步操作失败并显示 XmlWriterSettings.OutputMethod = Html