![](/img/trans.png)
[英]The given value of type String from the data source cannot be converted to type int of the specified target column.'
[英]Sorting a converted String to DateTime column.
我的DataTable有一個Date列,該列必須接受幾種不同的DateTime格式。 我想將這些合並為一種形式,然后按日期進行相應排序。
到目前為止,我已經編寫了以下代碼來更改日期的顯示方式。 但是它仍然不能正確排序。 顯示的內容不是排序時使用的內容。 它仍然使用舊格式。
因此2018-05-30仍會在2018-09-05之后,因為系統正在讀取數據,然后將其轉換為30/05/2018和05/09/2018。 並且由於30> 05,因此排序不正確。 有人有什么建議嗎?
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;
}
}
你有沒有嘗試過
List<DateTime> yourdateTime = new List<DateTime>();
yourdateTime.OrderBy(x => x.Date);
也看
yourdateTime.OrderBy(x => x.Date.TimeOfDay)
.ThenBy(x => x.Date.Date)
.ThenBy(x => x.Date.Year);
進入Date Class
您可以通過多種方式對其進行排序。 只需確保是否使用多個來先使用OrderBy
,然后再使用ThenBy
進行后續ThenBy
。
如果您的日期列/屬性被調用,則將DataGridColumn
的SortMemberPath
屬性設置為“ Date”。 然后,無論格式如何,都應按此屬性對列進行排序。
但是您不需要使用轉換器來格式化日期。 您可以只設置綁定的StringFormat
屬性:
if (e.PropertyName.Contains("Date"))
{
DataGridTextColumn dgtc = e.Column as DataGridTextColumn;
dgtc.Binding = new Binding(e.PropertyName) { StringFormat = "yyyy-MM-dd" };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.