Working with Null values in ASP.NET
Home > ASP > Null Values
One problem that often tricks me in ASP.net is the presence of null values.
This article describes how to deal with null strings and null database values.
Null strings
It is not immediately obvious that a null string is not our old friend "".
You would think that if a string contained nothing, it would be null, but it
isn't. A null string is a string that hasn't been assigned a value, but an empty
string is a string that has been assigned an empty value.
You can check if a string is null by using this:
if (myString == null) { do this or that; }
If you try to find the length of a null string, you can get this rather terse
error message:
Object reference not set to an instance
of an object.
So, it is best to check that the string isn't null first, then try to find
its length. You may end up with a null string if you tried to assign a string
to a value in a collection, and the value was not present in the collection.
You're unlikely to set a string to null yourself, and due to the fact that they
are confusing to work with, I don't recommend trying it.
Null Database Values
You can use the useful IsDBNull method to find out if something you have read
from a database is a null value. This is an important thing to do, because often
you will assume that a field called "bank_balance" in a database,
that is a numeric type, must hold a numeric value. But you'd be wrong, because
maybe it holds a null value. So, whenever I am reading from
a database, I check if the value is null before getting it:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(1))
{
bool title_only = reader.GetBoolean(1);
}
}
(For more information about SQL, see my SQL Server
page.)
In Visual Basic you can do this:
If reader3.Item(2) IsNot DBNull.Value Then hours += reader3.Item(2)
Conclusion
Null can trick you in many ways, so always think "could this value ever
contain null?" and if so, take precautions.
This page was last updated on 6 November 2006
|