null error

  • Thread starter Thread starter JFB
  • Start date Start date
J

JFB

Hi All,
In my function bellow I try to check for a null or empty value coming from
my database before I set my phone format.
Function Format(ByVal value As Object)

'LabelTest.Text = value

If (Not value Is DBNull.Value) And (value <> "") Then

Dim n As Long = Convert.ToInt64(value)

Return n.ToString("###-###-####")

End If

End Function

I have an error on If (Not value Is DBNull.Value) And (value <> "") Then:
System.InvalidCastException: Operator is not valid for type 'DBNull' and
string "".
How can I fix this?
Tks in advance
JFB
 
JFB schreef:
I have an error on If (Not value Is DBNull.Value) And (value <> "") Then:
System.InvalidCastException: Operator is not valid for type 'DBNull' and
string "".

value is of type Object... "" is of type String..

You could try to cast the value to a string, and then compware it with
string.Empty (the preferred alternative over "").
 
The problem may be that the second half of your If statement is throwing the
exception because you are using And. AndAlso & OrElse are short-circuit
boolean operators, which means that if the left side succeeds, the right side
never gets evaluated. Try rewriting it like this:

If (Not value Is DBNull.Value) AndAlso (value <> "") Then

Also, if you're using .NET 2.0, you can use IsNot:

If (value IsNot DBNull.Value) AndAlso (value <> "") Then

In either case, if value is null, the left side returns False so there is no
need for right side to be evaluated.

Tony
 
An object does not equal DBNull.Value - it would be Nothing, so say
If Not value is Nothing Then

and then check for the data type, if it is a string, then check for <> "".

T
 
Back
Top