|
Avoid boolean comparison errors in ASP
Often in VBScript, you'll want to determine if a numeric value is greater than zero then
perform some action based on the results. For example, you'll often want to know if a
recordset contains records. To do so, you can simply use the results in a boolean
expression, like so If rst.RecordCount Then 'Do something End If
This works because VBScript, like VB and VBA, considers any non- zero number
(negative or positive) a True boolean value. Be warned, however, that bugs can
occur when you try to use Not with this same expression, as in If Not rst.RecordCount
Then You might think this test would determine if the recordset didn't contain records.
It does when the RecordCount property returns -1 ((Not -1) = 0). However, if the
property returns the actual number of records, then this condition statement
returns True. That's because when you use Not on a number, VBScript returns the
opposite value of that number minus one. For instance, the expression Not 15
returns -16, which as you know VBScript interprets as True. With regard to the
record count test, if the property returns -1, then there's no problem, since the result is (1-1) or 0.
However, when the property contains an actual value, then Not rst.RecordCount
evaluates to a non-zero number, which again VBScript evaluates as True. To get
around this minor glitch, you can use one of the following statments:
If Not Cbool(rst.RecordCount) Then
or
If Not (rst.RecordCount<>0) Then
or simply
If rst.RecordCount = 0 Then

|