My DataTable has a Date column which must accept several different DateTime formats. I'd like to consolidate these under one form and then sort accordingly by date.
So far I've written the code below to change the way the date is displayed. But it still doesn't sort properly. What's displayed isn't what's used when sorting. It still uses the old format.
So 2018-05-30 still goes after 2018-09-05 because the system is reading the data before it was converted as 30/05/2018 and 05/09/2018. and because 30 > 05 it sorts improperly. Anyone have any suggestions?
if (e.PropertyName.Contains("Date"))
{
DataGridTextColumn dgtc = e.Column as DataGridTextColumn;
DateTimeConverter con = new DateTimeConverter();
(dgtc.Binding as Binding).Converter = con;
}
public class DateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
try
{
return DateTime.Parse(value.ToString()).ToString("yyyy-MM-dd");
}
catch
{
return value;
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value.GetType() == typeof(System.DateTime))
{
DateTime t = (DateTime)value;
return t.ToShortDateString();
}
return value;
}
}
have you tried
List<DateTime> yourdateTime = new List<DateTime>();
yourdateTime.OrderBy(x => x.Date);
also look at
yourdateTime.OrderBy(x => x.Date.TimeOfDay)
.ThenBy(x => x.Date.Date)
.ThenBy(x => x.Date.Year);
once you are into the Date Class
you have lots of ways to sort it. just make sure if you use more than one to use OrderBy
first and ThenBy
for subsequent passes.
Set the SortMemberPath
property of the DataGridColumn
to "Date" if this is what your date column/property is called. Then it should sort the column by this property regardless of the formatting.
But you don't need to use a converter to format the date. You could just set the StringFormat
property of the binding:
if (e.PropertyName.Contains("Date"))
{
DataGridTextColumn dgtc = e.Column as DataGridTextColumn;
dgtc.Binding = new Binding(e.PropertyName) { StringFormat = "yyyy-MM-dd" };
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.