Eurodata Computing Logo Technical Tips



Tip : 4
Technology : VB
Title : Coping with Null Strings in VB
If you try a string operation on a string containing a null it will generate a runtime error. Null strings can often occur when using ADO recordsets to access a database, for instance the following code retrieves a field from an opened recordset :

   Dim strMyString as string
   strMyString = rsRecordset.Fields(0)

If the value of rsRecordset.Fields(0) is null you will get an ‘Invalid Use of Null’ runtime error. You can of course get around this by using the IsNull function to test for this condition first :

   Dim strMyString as string
   If not IsNull(rsRecordset.Fields(0)) then
    strMyString = rsRecordset.Fields(0)
    ‘ handle a null value in the field
   End if

This is a good solution if your business rules require that nulls cause specific program actions to occur, however often nulls will only occur because there are data or logic errors and we just want to avoid a runtime error. A simple solution is to prepend an empty string to the field, as follows :

   Dim strMyString as string
   strMyString = "" & rsRecordset.Fields(0)

Now if the field value is null the result of the concatenation will be an empty string and no runtime error occurs.

Need further technical assistance ? Click here for more technical information.

Tech Tip Index

This article is provided 'as is' and no responsibility can be accepted for any errors. No part of this article may be used or reproduced in any fashion without the prior consent of Eurodata Computing Ltd. For syndication enquiries please contact us.
Site designed and maintained by Eurodata Computing
© Eurodata Computing 2000-13    Last updated : April 2013
Valid XHTML 1.0 Transitional Valid CSS!