开发者

Converting null string to date

开发者 https://www.devze.com 2023-03-14 21:57 出处:网络
I have searched high and low to no avail,and this is last step before completing my project so please help!Thanks in advance!

I have searched high and low to no avail, and this is last step before completing my project so please help! Thanks in advance!

The user will select an entry in a gridview, which then redirects them to a form that is populated with the data from the selected row (thus making the gridview editable in a more user friendly way). Null values are accepted by the DB and I would like to show null date values as blank (or " ") in the corresponding text boxes. Instead I get the error:

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

Here is my code:

'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 开发者_JAVA百科= sold
        DetailTXTbox.Text = detail
        'etc, etc
    End Sub

I used the function mycstr to fix the dbnull to string error but it does not seem as simple to adapt to "date" data type

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


try this when you read the values from the reader with all your dates, this will first test to see if the date is dbnull, if it is then it will assign a nothing value and you should get your desired empty cell, otherwise it will show the date:

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


Have you tried using the Convert.IsDBNull function?

Here is the official documentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号