1

I have added dummy data to my SQL database. When I try to run the VB it comes back with a null error.

What I have done is delete the dummy data from the database so it not reading the null value anymore. Even after deleting it the VB file is still throwing the error like the null values are still there. I have run a sql script to check and I can confirm it not longer there.

Here is the line of code that throwing the error.

If Date.Now.AddDays(LoadsFilter * -1) > Convert.ToDateTime(myReader(2)) Then
    ShowLoad = 0 
End If

I'm still quite new to vb so I'm not sure what to do here. I was thinking of passing a method to read null values but I have already deleted the null value. I'm not sure how to go about this, can anyone help please?

5
  • You need to check if myReader(2) is returning null before you use it. Commented Aug 19, 2021 at 9:03
  • Yes it is 'If IsDBNull(myReader(2)) Then myHtml = myHtml + "<td></td>" ' that why i'm confused abit Commented Aug 19, 2021 at 9:07
  • Are you checking the reader has rows returned also? Commented Aug 19, 2021 at 9:11
  • it returning values as i can see it in the table. so I know it working. but i have delete the dummy data, does it still need to be throwing this error? Commented Aug 19, 2021 at 9:26
  • Are you sure you are connected to the right database? Commented Aug 20, 2021 at 8:19

1 Answer 1

2

There's no need for any conversion. The data reader has its own methods for null tests and for getting data in the appropriate type, e.g.

If Not myDataReader.IsDBNull(2) Then
    Dim dt = myDataReader.GetDateTime(2)

    'Use dt here.
End If

You can also use a single line to get a Nullable(Of Date):

Dim dt = If(myDataReader.IsDBNull(2), New Date?, myDataReader.GetDateTime(2))

Note that, if you prefer to use column names rather than indexes, which make your code clearer, then you can use the GetOrdinal method, as those other methods only support indexes:

Dim dt = If(myDataReader.IsDBNull(myDataReader.GetOrdinal("ColumnName")),
            New Date?,
            myDataReader.GetDateTime(myDataReader.GetOrdinal("ColumnName")))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.