使日期为空

时间:2010-09-02 15:57:19

标签: c# vb.net

有人可以帮我修复我的代码我试图通过一个除了_dtSWO之外的函数将null放在sql server中。

如果我设置_dtSWO = Nothing,则返回#12:00:00 AM#,它会抛出异常。该字段在sql server中可以为空,我只想让它返回一个空白

Dim _swoDate As String = udSWOReceivedDateDateEdit.Text
        Dim _dtSWO As Date

        If _swoDate <> "" Then
            _dtSWO = Date.Parse(udSWOReceivedDateDateEdit.Text)
        Else
            'THIS DOESNT WORK
            _dtSWO = Nothing
        End If

2 个答案:

答案 0 :(得分:4)

您需要使用Nullable类型。默认情况下,Date不会为null(在VB.Net中为Nothing)作为值。 Nullable types接受null(Nothing)。

    Dim _dtSWO As Nullable(Of Date)

    If String.IsNullOrEmpty(_swoDate) Then
        _dtSWO = Date.Parse(udSWOReceivedDateDateEdit.Text)
    Else
        _dtSWO = Nothing
    End If

根据评论进行编辑。

答案 1 :(得分:1)

让它为Nullable。与Nullable Integer问题相同的情况。

Dim _swoDate As String = udSWOReceivedDateDateEdit.Text
Dim _dtSWO As Date?

If _swoDate <> "" Then
    _dtSWO = Date.Parse(udSWOReceivedDateDateEdit.Text)
Else
    _dtSWO = Nothing
End If