I frequently have problems dealing with DataRows
returned from SqlDataAdapters
. When I try to fill in an object using code like this:
DataRow row = ds.Tables[0].Rows[0]; string value = (string)row;
What is the best way to deal with DBNull's
in this type of situation.
return String. Empty; Please do not confuse the notion of null in C# language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object, whereas DBNull represents an uninitialized field or nonexistent database column.
The DBNull class represents a nonexistent value. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.
DbNull is not the same as Nothing or an empty string. DbNull is used to denote the fact that a variable contains a missing or nonexistent value, and it is used primarily in the context of database field values. Since any expression that contains DbNull evaluates to DbNull , an expression such as: If var = DbNull Then.
Nullable types are good, but only for types that are not nullable to begin with.
To make a type "nullable" append a question mark to the type, for example:
int? value = 5;
I would also recommend using the "as
" keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is
as
" keyword returns null
if a value is DBNull
.as
, but coupled with the reason above it's useful.I'd recommend doing something like this
DataRow row = ds.Tables[0].Rows[0]; string value = row as string;
In the case above, if row
comes back as DBNull
, then value
will become null
instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, using as
will cause your code to silently fail and make values simple null
instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With