Handle NULL in reader?

Q

qqq

I have the following code to read from an Access db with
Provider=Microsoft.Jet.OLEDB.4.0 (code simplified here):

Dim cmd As New System.Data.OleDb.OleDbCommand("Select numbookings from
TblEvents where Entid=33", conn)
Dim Reader As System.Data.OleDb.OleDbDataReader = cmd.ExecuteReader()
If Reader.Read() Then
x=Reader.GetInt16(0).ToString
End If

This fails if the value for numbookings is NULL with the following error:
Run-time exception thrown : System.InvalidOperationException - The provider
could not determine the Int16 value. For example, the row was just created,
the default for the Int16 column was not available, and the consumer had not
yet set a new Int16 value.

How can I detect the NULL value? I've played with IsDbNull etc, but can't
get it to work. I also tried using the Access NZ function in the SQL
command, but get 'unrecognized function'.
Thanks for any help,
Paul.
 
Q

qqq

Care to elaborate a little bit (e.g. show me one line of code)? I tried to
get this to work and couldn't.

Thanks,

Paul.
 
J

Jay B. Harlow [MVP - Outlook]

qqq,
As Lucas suggested use System.DBNull' to see if the first field is a
database NULL or not.

The easiest way to check for System.DBNull is to use the
OleDbDataReader.IsDBNull method.

If Reader.Read() Then
If Not Reader.IsDBNull(0) Then
x = Reader.GetInt16(0).ToString
End If
End If

Hope this helps
Jay
 

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

Top