【问题标题】:Format null DateTime in DataGridView WinForm在 DataGridView WinForm 中格式化 null DateTime
【发布时间】:2012-05-15 10:50:05
【问题描述】:

如何在 datagridview 中格式化空日期时间? 我以编程方式创建 datagridview 列,在表单加载中

DataGridViewCellStyle style = new DataGridViewCellStyle();
style.Format = "dd-MM-yyyy";

DataGridViewTextBoxColumn updatedDateColumn = new DataGridViewTextBoxColumn();
updatedDateColumn.DataPropertyName = "UpdatedDate";
updatedDateColumn.HeaderText = "Updated Date";
updatedDateColumn.Name = "UpdatedDate";
updatedDateColumn.DefaultCellStyle = style;

问题是当更新日期值为空时 datagridview 显示 01/01/0001 12:00:00

我尝试过编辑

style.NullValue = string.Empty;

但是没用 如何解决这个问题? 谢谢

【问题讨论】:

  • DateTime 是一个值类型,所以它永远不可能是null。你到底在细胞里放的是什么?
  • 是的,你是对的,当我从数据库中获取 updatedDate 时,我检查 updatedDate 是否为空,我将 updatedDate 分配给 DateTime.MinValue。但如果我不应用样式,updatedDate 不会显示 01/01/0001 12:00:00
  • 为什么不改用Nullable<DateTime>?这似乎可以解决问题,并且感觉也更合适。
  • 你能给我看看这个例子吗?
  • 我不能,因为我不知道你的代码是什么样的。您需要更改存储日期的属性的类型。

标签: c# winforms datetime datagridview formatting


【解决方案1】:

您可以在sql server中使用ISNULL将null date设置为null,并将datagridviewCellStyle的NullValue属性设置为string.Empty;像这个在 sql server 中的

ISNULL(DateColumnName , NULL) and set style.NullValue = string.Empty   

在dataGridViewCellStyle中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多