2011-06-24 115 views
1

我已經搜索了高和低無效,這是完成我的項目之前的最後一步,所以請幫助!提前致謝!將空字符串轉換爲日期

用戶將在gridview中選擇一個條目,然後將它們重定向到一個填充了選定行數據的表單(從而使gridview以更加用戶友好的方式編輯)。數據庫接受空值,我希望在相應的文本框中顯示空值(或「」)。相反,我得到的錯誤:

Conversion from type 'DBNull' to type 'Date' is not valid.

這裏是我的代碼:

'preceded by connection code  
Dim sqlcmd As String = "SELECT * from Master WHERE RecNum = @recnum" 
     'Dim sqlCmd As New OleDb.OleDbCommand("SELECT * from Master WHERE RecNum = @recnum", connection) 
     Dim FileCommand3 As New OleDb.OleDbCommand(sqlcmd, connection) 
     FileCommand3.Parameters.AddWithValue("@recnum", user) 
     Dim Reader3 As OleDb.OleDbDataReader = FileCommand3.ExecuteReader() 
     If Reader3.Read Then 

      stock = myCStr(Reader3("StockNum")) 
      make = myCStr(Reader3("Make")) 
      color = myCStr(Reader3("Color")) 
      stockin = myCStr(Reader3("Stockin")) 
      ucistart = myCStr(Reader3("UCIStartDate")) 
      repairs = Reader3("Repairs") 
      tires = Reader3("tiresneeded") 
      onlot = Reader3("onlot") 
      sold = Reader3("sold") 
      year = myCStr(Reader3("year")) 
      model = myCStr(Reader3("model")) 
      location = Reader3("location") 
      srvcRO = myCStr(Reader3("svcROnum")) 
      ucicompldate = myCStr(Reader3("uciestcompletedate")) 
      collRO = myCStr(Reader3("collisionROnum")) 
      other = myCStr(Reader3("other")) 
      offprop = Reader3("offProperty") 
      detail = (Reader3("detail") 
     End If 
     connection.Close() 

     SoldCheckBX.Checked = sold 
     DetailTXTbox.Text = detail 
     'etc, etc 
    End Sub 

我用的功能mycstr固定的DBNull串錯誤,但它似乎並沒有那麼簡單,以適應「日期」數據類型

Function myCStr(ByVal test As Object) As String 
    If isdbnull(test) Then 
     Return ("") 
    Else 
     Return CStr(test) 
    End If 
End Function 

回答

2

當您從閱讀器讀取所有日期的值時,請嘗試此操作,這將首先測試以查看日期是否爲dbnull,如果是則它將分配一個空值,並且您應該獲得所需的空單元格,否則會顯示日期:

ucistart = IIf(reader3("UCIStartDate") Is DBNull.Value, Nothing, reader3("UCIStartDate")) 
+0

不要忘記在保存時補償另一端,如果日期沒有在代碼中設置。 @ucistart = IIf(myObj.date爲null,DBNull.Value,myObj.Date); – Fellmeister

+0

謝謝!那是做的!......唯一的是,我仍然在細胞中獲得時間。我宣佈ucistart爲Date ...我怎麼能把它設置爲沒有時間的日期? – JDV590

+0

很酷,你可以格式化datagrid來只顯示日期,在gridview列中設置dataformat字符串爲:dataformatstring =「{0:M-dd-yyyy}」其中字符串是你想要的格式 –

0

您是否嘗試過使用Convert.IsDBNull功能?

Here是官方文檔。