Working with null database values

G

George G.

Hi there,

I hope I am posting to the correct news group. What would be a good way to
deal with null database values using ADO.NET. My SQL queries sometimes
return null values when I have left outer joints for example and when I use
GetString() or GetInt32() from DBReader I get an error -
System.InvalidCastException: Specified cast is not valid. I know that one
way to correct this is to make sure the SQL queries never return null
values, but there must be more elegant way of fixing it.

TIA, regards,
George
 
M

Mark Rae

I hope I am posting to the correct news group. What would be a good way to
deal with null database values using ADO.NET. My SQL queries sometimes
return null values when I have left outer joints for example and when I
use GetString() or GetInt32() from DBReader I get an error -
System.InvalidCastException: Specified cast is not valid. I know that one
way to correct this is to make sure the SQL queries never return null
values, but there must be more elegant way of fixing it.

Let's say, for example, that you are displaying details of a single record
in a SQL Server table which has a DateTime field called dtmCompleted. When
the record is created, this field will be null because it hasn't been
completed yet. However, at some time in the future the field will contain
the datetime that the record was completed.

You have a Label called lblCompleted on your WebForm, and you populate it
from a SqlDataReader called objDR.

lblCompleted.Text = (objDR["dtmCompleted"] == DBNull.Value ? " " :
Convert.ToDateTime(objDR["dtmCompleted"]).ToString("dd MMM yyyy HH:mm"));
 
E

Eliyahu Goldin

George,

You can always check if the value is null prior to refereing to it. Method
IsDBNull().

Eliyahu
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top