防止格式化的空日期

时间:2017-05-01 14:46:34

标签: c# .net winforms linq datagridview

我正在将datagridview数据源设置为对象列表:

grdCurrentMissions.DataSource = _CurrentMissions.Select(o => new
                {
                    column1 = o.ScheduledTime.ToString(@"hh\:mm\:ss"),
                    column2 = o.DepartureTime.ToString(@"hh\:mm\:ss")
                }).ToList();

日期字符串格式适用于现有日期值,但空值显示为12:00 o' clock,如何防止这种情况?

1 个答案:

答案 0 :(得分:4)

假设ScheduledTime和DepartureTime是DateTime属性,则在未填写时属性等于DateTime.MinValue。因此您可以检查:

grdCurrentMissions.DataSource = currentMissions.Select(o => new
        {
            column1 = o.ScheduledTime == DateTime.MinValue ? "-" : o.ScheduledTime.ToString(@"hh\:mm\:ss"),
            column1 = o.DepartureTime == DateTime.MinValue ? "-" : o.DepartureTime.ToString(@"hh\:mm\:ss"),
        }).ToList();