Reading NullValues
As you learned in Chapter 2
, a column defined as null can store a null value. A null value
indicates that the column value is unknown. A standard C# type cannot store a null value,
but a Sql* type can.
Let's consider an example of reading a null value from the database. Say you've
performed a SELECT statement that retrieves the UnitPrice column for a row from the
Products table, and that the UnitPrice column contains a null value. If you try to store that
null value in a standard C# type (such as a decimal) using the following code:
decimal unitPrice =
productsSqlDataReader.GetDecimal(unitPriceColPos);
then you'll get the following exception:
System.Data.SqlTypes.SqlNullValueException
You'll also get this exception if you try to store the null value in an object, as shown in
the following example:
object unitPriceObj =
productsSqlDataReader["UnitPrice"];
You can check if a column contains a null value using the IsDBNull() method of a
DataReader object. This method returns a Boolean true or false value that indicates
whether the column value is null. You can then use that Boolean result to decide what to
do. For example:
if (productsSqlDataReader.IsDBNull(unitPriceColPos))
{
Console.WriteLine("UnitPrice column contains a null value");
}
else
{
unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);
}
Because productsSqlDataReader.IsDBNull(unitPriceColPos) returns true, this example
displays:
UnitPrice column contains a null value
As mentioned, a Sql* type can store a null value. A null value is stored as Null. For
example:
SqlMoney unitPrice =
productsSqlDataReader.GetSqlMoney(unitPriceColPos);
Console.WriteLine("unitPrice = " + unitPrice);
This example displays:
unitPrice = Null
Each of the Sql* types also has a Boolean property named IsNull that is true when the
Sql* object contains a null value. For example:
Console.WriteLine("unitPrice.IsNull = " + unitPrice.IsNull);
This example displays:
unitPrice.IsNull = True
True is displayed because unitPrice contains Null.
.
Reading Null Values
As you learned in Chapter 2
, a column defined as null can store a null value. A null value
indicates that.
displays:
UnitPrice column contains a null value
As mentioned, a Sql* type can store a null value. A null value is stored as Null. For
example:
SqlMoney unitPrice