c# - 如何按日期对 DataGridView 列(绑定(bind)到 BindingSource)进行排序?

标签 c# .net winforms datagridview bindingsource

我有一个 DataGridView,其中包括包含日期的列。不幸的是,日期的格式为 DD.MM.YYYY 并且整个值位于 1 列中,这是欧洲常见的日期格式。 DGV 绑定(bind)到能够进行排序和高级排序的 BindingSource。

问题如下:如果我只使用 DGV 的标准排序,日期将被视为字符串(它们显示在 DataGridViewTextBoxColumn 中),因此按日->月->年排序,当然我倒要恰恰相反;我希望它们按时间顺序排序。

那么,有没有办法按照我希望的方式对这些列进行排序?

  • 到目前为止,最简单的方法是能够使用 SortCompare DGV 的事件,但显然如果 DGV 被绑定(bind)则无法完成 到数据源。
  • 当然,我使用了 Google,并且总是得到“使用 Sort 属性进行高级排序”的解决方案。绑定(bind)到 DGV 的 BindingSource 确实支持排序和高级排序,但据我了解,这只是让我有可能例如按多列排序,不提供按年->月->日对日期列进行排序的方法(或更一般的术语允许我实现一种比较功能)。还是我遗漏了什么?

我有哪些选择来实现我想要的?在解释时,请记住,我对这种 Windows 窗体的东西 - 虽然不是编程新手 - 是新手。

提前致谢!

最佳答案

private void DataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    if (e.Column.Name == "YourColumnName") //<== this must be your date column name
    {
        DateTime dt1 = Convert.ToDateTime(e.CellValue1);
        DateTime dt2 = Convert.ToDateTime(e.CellValue2);
        e.SortResult = System.DateTime.Compare(dt1, dt2);
        e.Handled = true;
    }
}

关于c# - 如何按日期对 DataGridView 列(绑定(bind)到 BindingSource)进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9530064/

相关文章:

c# - 异步数据读取器和执行顺序

c# - 如何使用 .Net 4.0 中的 HttpClient 将 XML 响应解析为 .Net 类?

.net - 多线程Random.NextDouble()

c# - Windows 7 中的鼠标移动 - 左键单击并拖动

c# - 以编程方式将我的资源中的图片设置为 PictureBox

c# - 如何使用类库中的 Controller ?

c# - 为什么 Entity Framework 中的子实体包含引用父实体的虚拟属性?

c# - 我们可以对未实现 IDisposable 的对象使用 Using 语句吗

c# - MethodInvoker 的区别?

c# - 如何通过同步实现 C# Winforms 数据库应用程序?