我有一个DataGridView,其中包含包含日期的列。不幸的是,日期的格式为DD.MM.YYYY,整个值为1列,这是欧洲的常用日期格式。 DGV与BindingSource绑定,后者能够进行排序和高级排序。
问题如下:如果我只使用DGV的标准排序,则日期被视为字符串(它们显示在DataGridViewTextBoxColumn中),因此按日 - >月 - >年分类,但是当然我想要完全相反;我希望它们按时间顺序排序。
那么,有没有办法按照我希望的方式对这些列进行排序?
我有什么选择可以实现我想要的?在解释时,请记住,我对这个Windows窗体的新功能并不陌生。
提前致谢!
答案 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();
}
}
}
希望这有帮助!