If you are retrieving or adding values from and to your database then you will know the difficulties that can be caused by NULL values. The notorious InvalidCastException is one example of receiving a NULL value from your database into an ASP.NET object that doesn’t know what to do with database NULL values.
Here’s typical example of an InvalidCastException error caused by setting a String variable to a value that is returned as a NULL from your database query:
System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid. at Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object Value) at ASP.myPageName_aspx.Page_Load(Object sender, EventArgs e) in D:\Inetpub\wwwroot\MySite\myPageName.aspx:line 1xx
By definition, a scalar query will return the first column of the first row of a database query. In plain English this means it will return a single value. This can come in handy at times.
In the next series of articles I will cover the basic data connections including basic examples in C# and VB.NET.
One thing to note from the examples below is that I am using a try – catch – finally syntax to handle the clean-up of the command and connection objects. As an alternate syntax, you can make use of the Using object to handle the cleanup.