如何按日期对DataGridView列(绑定到BindingSource)进行排序?
问题描述:
我有一个DataGridView,其中包含有包含日期的列。不幸的是,日期的格式为DD.MM.YYYY,整个值为1列,这是欧洲的通用日期格式。 DGV绑定到一个能够进行排序和高级排序的BindingSource。如何按日期对DataGridView列(绑定到BindingSource)进行排序?
问题是:如果我只是使用DGV的标准排序,日期被视为字符串(它们显示在DataGridViewTextBoxColumn中),因此按日 - >月 - >年排序,但当然我想完全相反;我希望他们按照时间顺序排序。
那么,有没有办法按照我想要的方式对这些列进行排序呢?
- 目前最简单的方法是能够使用DGV的SortCompare 事件,但显然,如果DGV绑 到DataSoruce无法做到的。
- 当然我使用Google,我总是得到“使用排序属性进行高级排序”的解决方案。绑定到DGV的BindingSource确实支持排序和高级排序,但据我所知,这只是使我有可能按多列排序,但不提供按年 - >月 - >日对日期列进行排序的方法(或者更一般地说,允许我实现一种比较功能)。或者我错过了什么?
我有什么选择可以实现我想要的功能?在解释时,请记住我是 - 对编程不熟悉的人 - 对这个Windows Forms的新东西不熟悉。
在此先感谢!
答
也许这段代码会给你一个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();
}
}
}
希望这有助于!
答
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;
}
}
看一看这篇文章,看看是否有帮助:DGV排序使用日期(http://stackoverflow.com/questions/857115/how-to-sort-a-datagridview-column) – Void 2012-03-02 08:23:01
这绝对是诀窍,非常感谢你! – Yuk 2012-03-05 09:04:33