2010-09-02 72 views
0

有人可以幫我修復我的代碼我試圖通過除了_dtSWO的函數在SQL服務器中的空值。使一個日期爲空

如果我設置了_dtSWO = Nothing,它會返回#12:00:00 AM#,這會引發異常。該字段在SQL服務器中可以爲空我只希望它返回空白

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 

回答

4

您需要使用Nullable類型。默認情況下,Date不會將null(VB.Net中的Nothing)作爲值。 Nullable types do accept null(Nothing)。

Dim _dtSWO As Nullable(Of Date) 

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

根據評論編輯。

+2

您可能還想捕獲空字符串大小寫;而不是比較空字符串,我會使用'String.IsNullOrEmpty()'。 – tdammers 2010-09-02 16:03:27

1

使其可空。與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 
+0

是嗎?在VB中標記? – Martin 2010-09-02 16:01:51

+0

問號是速記。在VB.NET中工作,但我通常沒有看到它在很多VB.NET的例子在線使用。 – Larsenal 2010-09-02 16:02:58

+0

它一開始並不是有效的語法,但稍後添加了:http://stackoverflow.com/questions/223844/history-of-vb-net-nullable-syntax – jball 2010-09-02 16:04:13