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?
Advertisement
Answer
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")))