Null DB fields causing an error

G

Guest

Below is the code I am using to display a list of values from a table row the
problem is some of these columns may be null. Currently when I execute this
code I get the following error: "Cast from type 'DBNull' to type 'String' is
not valid."

This error is caused by the null values. How can I avoid this error?

Dim i As Integer = QueueReader.GetOrdinal("CustomerId")

If QueueReader.Read() And Not QueueReader.IsDBNull(i) Then
lblJanuary.Text = QueueReader("January")
lblFebruary.Text = QueueReader("February")
lblMarch.Text = QueueReader("March")
lblApril.Text = QueueReader("April")
lblMay.Text = QueueReader("May")
lblJune.Text = QueueReader("June")
lblJuly.Text = QueueReader("July")
lblAugust.Text = QueueReader("August")
lblSeptember.Text = QueueReader("September")
lblOctober.Text = QueueReader("October")
lblNovember.Text = QueueReader("November")
lblDecember.Text = QueueReader("December")
End If


Thanks, Justin
 
K

Karl Seguin

isn't it possible that one of the months has a null value in it?

if so you need to check for null on each of them.

Karl
 
T

Tarren

For the fields that could contain NULL values, you must do a check for
DBNULL

Below is an example of one way.

For me I write a function for the page, so my code would look like the
following

Dim i As Integer = QueueReader.GetOrdinal("CustomerId")

If QueueReader.Read() And Not QueueReader.IsDBNull(i) Then
If Not IsDBNull(QueueReader("January")) Then lblJanuary.Text
= QueueReader("January")
If Not IsDBNull(QueueReader("February")) Then
lblFebruary.Text = QueueReader("February")
'And the rest would take similar form
End If
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,616
Members
45,306
Latest member
TeddyWeath

Latest Threads

Top