【问题标题】:Make A Date Null使日期为空
【发布时间】:2011-04-07 10:21:41
【问题描述】:

有人可以帮我修复我的代码吗?我试图通过除 _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

【问题讨论】:

    标签: c# vb.net


    【解决方案1】:

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

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

    根据评论编辑。

    【讨论】:

    • 您可能还想捕捉空字符串大小写;我不会与空字符串文字进行比较,而是使用String.IsNullOrEmpty()
    【解决方案2】:

    使其可以为空。与您的 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
    

    【讨论】:

    • 问号是简写。在 VB.NET 中工作,尽管我通常看不到它在许多在线 VB.NET 示例中使用。
    • 一开始是无效的语法,后来添加了:stackoverflow.com/questions/223844/…
    • 我相信当第一次引入可空类型时,? 在 VB 中不可用。然而,在某个时候,这种能力被添加了。
    猜你喜欢
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2021-07-28
    • 2013-12-22
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多