The DBNull Class and isDBNull Function

When working with a database, a value for a given column may not be defined. For a reference type this isn't a problem, as it is possible to set reference types to Nothing. However, for value types, it is necessary to determine whether a given column from the database or other source has an actual value prior to attempting to assign a potentially null value. The first way to manage this task is to leverage the DBNull class and the IsDBNull function. This class is part of the system namespace, and you reference it as part of a comparison. The IsDBNull function accepts an object as its parameter and returns a Boolean that indicates whether the variable has been initialized. The following snippet shows two values, one a string being initialized to Nothing and the other being initialized as DBNull.Value:

Private sub NullValues()

Dim strNothing As string = Nothing Dim objectNull As Object = DBNull.Value TextBoxl.Text = "" If IsDBNull(strNothing) Then

TextBoxl.Text = "But strNothing is not the same as Null." End If

If system.DBNull.Value.Equals(objectNull) Then

TextBoxl.Text &= "objectNull is null." & Environment.NewLine End If End sub

The output of this code is shown in Figure 2-10. In this code, the strNothing variable is declared and initialized to Nothing. The first conditional is evaluated to False, which may seem counterintuitive, but in fact VB differentiates between a local value, which might not be assigned, and the actual DBNull value. This can be a bit misleading, because it means that you need to separately check for values which are Nothing. The second conditional references the second variable, objectNull. This value has been explicitly defined as being a DBNull.Value as part of its initialization. This is similar to how a null value would be returned from the database. The second condition evaluates to True. While DBNull is available, in most cases, developers now leverage the generic Nullable class described in Chapter 8, rather than working with DBNull comparisons.

Was this article helpful?

0 0

Post a comment