Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将DateTime转换为DateTime?在asp.net中导致错误_C#_Asp.net_Datetime - Fatal编程技术网

C# 将DateTime转换为DateTime?在asp.net中导致错误

C# 将DateTime转换为DateTime?在asp.net中导致错误,c#,asp.net,datetime,C#,Asp.net,Datetime,在我的c#代码隐藏中,当我转换 public DateTime custDOB{get;set;} 到 公共日期时间?SubDOB{get;set;} 我的一个代码行出现错误 tboxDateOfBirth.Text=oCust.custDOB.toSortDateString() 消息读取的内容为“System.Nullable”不包含“ToSortDateString”的定义,并且找不到接受“System.Nullable”类型的第一个参数的扩展方法“ToSortDateString” 如何

在我的c#代码隐藏中,当我转换
public DateTime custDOB{get;set;}


公共日期时间?SubDOB{get;set;}

我的一个代码行出现错误
tboxDateOfBirth.Text=oCust.custDOB.toSortDateString()

消息读取的内容为“System.Nullable”不包含“ToSortDateString”的定义,并且找不到接受“System.Nullable”类型的第一个参数的扩展方法“ToSortDateString”

如何解决此问题?

将该行更改为

tboxDateOfBirth.Text = oCust.custDOB.HasValue? oCust.custDOB.Value.ToShortDateString() : string.Empty;

如果您始终100%确定它将有一个值且不为null,请执行此操作

tboxDateOfBirth.Text = ((DateTime)(oCust.custDOB)).ToShortDateString();
或者,如果有可能是空的,你可以选择安德烈·卡利的答案


您还应该阅读。

有可为空的类型,比如int?或者DateTime?,因此您可以使用
.HasValue
要访问实际值,请使用

oCust.custDOB.Value.ToShortDateString();

虽然你的问题的解决方法很简单,但措辞却很混乱。在您的第一行代码中将
custDOB
的类型更改为
DateTime?
。我认为您不能使用??运算符,因为它只允许我们在值为null时操作操作。