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

时间:2012-03-02 08:17:43

标签: c# .net winforms datagridview bindingsource

我有一个DataGridView,其中包含包含日期的列。不幸的是,日期的格式为DD.MM.YYYY,整个值为1列,这是欧洲的常用日期格式。 DGV与BindingSource绑定,后者能够进行排序和高级排序。

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

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

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

我有什么选择可以实现我想要的?在解释时,请记住,我对这个Windows窗体的新功能并不陌生。

提前致谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

也许这段代码会给你一个ideea。首先我要设置数据:

DataTable dt = new DataTable();
dt.Columns.Add("DateOfBirth", typeof(DateTime));

dt.Rows.Add(new DateTime(1981, 10, 29));
dt.Rows.Add(new DateTime(1984, 8, 12));
dt.Rows.Add(new DateTime(1982, 9, 7));

bindingSource1.DataSource = dt;
dataGridView1.DataSource = bindingSource1;
dataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.Programmatic;

现在使用ColumnHeaderMouseClick,我们将对第一列执行排序:

private SortOrder _sortDirection;

    private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
        if (e.ColumnIndex == 0) {
            string sort = string.Empty;
            switch (_sortDirection) {
                case SortOrder.None:
                    _sortDirection = SortOrder.Ascending;
                    sort = "asc";
                    break;
                case SortOrder.Ascending:
                    _sortDirection = SortOrder.Descending;
                    sort = "desc";
                    break;
                case SortOrder.Descending:
                    _sortDirection = SortOrder.None;
                    sort = string.Empty;
                    break;
            }

            dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = _sortDirection;
            if (!string.IsNullOrEmpty(sort)) {
                bindingSource1.Sort = "DateOfBirth " + sort;
            } else {
                bindingSource1.RemoveSort();
            }
        }
    }

希望这有帮助!