You can also test for NULL values in VB 6.0 by using the IsNull() function, as the following code shows:
If IsNull(rs("DateShipped")) Then
txtDateShipped.Text =
"<Unknown>"
Else
txtDateShipped.Text =
rs("DateShipped")
End If
However, this approach takes a little longer to code and execute because it uses late binding. VB 6.0's IsNull() function corresponds to Visual Basic .NET's IsDBNull() function, which I show in a moment.
Setting NULL Values in VB 6.0
Setting an updateable Recordset Field object's Value property to NULL is painless: You can use either the DBNull or Null keywords, as the following three code examples show:
rs("Author") = DBNull
' The third (2) Field object
' is "Author".
rs(2).Value = Null
rs.Fields(enuFields.Author).Value = DBNull
For this method to work, the Field object must be updateable and support NULL values. All three of the above lines of code produce the same result.
Testing for NULL Values in Visual Basic .NET
Visual Basic .NET (and the .NET Framework languages in general) support many techniques for handling NULL values, as the following code examples show. First, open a connection and run a query to return several columns in a rowset; in this case, the first column is always NULL. To simplify the code, I use the dv variable to hold the returned column value:
Dim dv As Object
dv = drReader.GetValue(0)
' Capture the first value from
' the data stream.
txtDateShipped.Text = "" &
dv.ToString
You can use any of the following techniques to test for NULL values in a specific item in the ADO.NET SqlDataReader object's Items collection, as I show laterto learn how to use the IsNULL() function to avoid NULLs, see the sidebar "Using T-SQL to Avoid Unwanted NULLs." Note that because I declare dv as an object, dv can contain a NULL value. If I don't declare dv as an object, ADO.NET will produce the exception message System
.InvalidCastException: Specified cast is not validbut not until the query returns a NULL.
Prev. page
1
[2]
3
next page