在 DataGridView 中对日期进行排序

Sorting dates in DataGridView

我正在使用 sqlDataReader 从 SQL table 中提取不同的信息。 其中一列包含 DateTime,从 sql 中提取并正确显示,使用:

var datestring = reader.GetDateTime(reader.GetOrdinal("deadline")).ToShortDateString();

它以下列格式显示在 DataGridView 中:dd.MM.yyyy

当我尝试对其进行排序时,无论 MMyyyy 信息是什么,它都会在 dd 之后进行排序。

使用以下命令将日期字符串放入数据网格视图中:

dgv_tasks.Rows.Add(tid, taskname, sidvariable, datestring);

任何人都知道为什么它根本不按日期排序,只按 dd 中的数字排序?

(我在这里寻找答案,但是 none 的类似问题有有效的答案)。

您想将其保留为 DataGridView 中的 DateTime,而不是将其转换为字符串。这就是为什么它按字母顺序而不是按日期排序的原因。

删除 .ToShortDateString() 并将 DataGridViewColumn 定义为 DateTime 类型(假设您手动创建列)。

将数据分配给 DataGridView 后,只需修改该列的 DefaultCellStyle.Format 值即可以您选择的任何方式显示日期:

dgv_tasks.Columns["deadline"].DefaultCellStyle.Format = "dd.MM.yyyy";

它按字母顺序排序,因为您将它转换为字符串。

尝试将数据网格视图中的日期值与用于显示目的的格式化程序一起使用。