0

I have the following function:

Public Shared Function imageExists(ByVal path As Object) As Boolean
                If IsDBNull(path) = False Or Not path Is Nothing Then
                    Dim pathString As String = Convert.ToString(path)
                    If Exists(HttpContext.Current.Server.MapPath(path)) Then
                        Return True
                    Else
                        Return False
                    End If
                Else
                    Return False
                End If

            End Function

Called by the visible property for this image control:

<asp:Image ID="img_SmallImage" runat="server" ImageUrl='<%# "~/Content/Images/Exclusive/" + Eval("trip_SmallImage") %>' Visible='<%# OnTheMain.Images.Validation.imageExists(Eval("trip_SmallImage"))%>' />

No matter what I try for the If IsDBNull part, it either ignores it and executes the code, or returns an error such as Conversion from type 'DBNull' to type 'String' is not valid.

How can I rectify the situation?

Community
  • 1
  • 1
StrattonL
  • 708
  • 1
  • 9
  • 24
  • Sorry, the 'or not nothing' was a mistake when I copied the code into the question. Unfortunately none of these answers worked. I tried changing the object to string, but to no avail. Is there anything else I can try? I just constantly get this error 'Conversion from type 'DBNull' to type 'String' is not valid.' – StrattonL Jan 26 '13 at 13:56
  • 1
    BTW, I am answering you to handle the exception, that not means that your question is logical, please edit your question first, – Alaa Alweish Jan 27 '13 at 08:52
  • Sorry, I'm not sure what you're trying to say. I have corrected the mistake if that's what you meant. The exception handling doesn't work I'm afraid, as I said, I've tried all three answers on this question. – StrattonL Jan 27 '13 at 23:38

3 Answers3

2

you have a logical error in the first if check.

Not Nothing always evaluates to true. so that first statement basically compiles down to:

If IsDBNull(path) Or True Then

which will always be true. your if statement should probably look like this:

If Not IsDBNull(path) And path Is Not Nothing Then
Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49
1

I don't know why you are using both IsDBNull and Nothing, anyway

Use AndAlso, it will not check the next part if previous is false

check the path first to prevent the exception:

        If path IsNot Nothing AndAlso IsDBNull(path) = False Then
        'do what ever you want to do
    End If

FYI, OrElse will do the same function for Or, for me i am using this short-circuiting logical operators by default read my question on this here

Community
  • 1
  • 1
Alaa Alweish
  • 8,904
  • 16
  • 57
  • 84
0

Use

If Not String.IsNullOrEmpty(path) Then

as you need to handle empty strings. You should be passing a String, not a generic Object. Also, you can't do Or Not Nothing. You would have to do Not IsDBNull(path) And Not path Is Nothing.

Edwin
  • 1,458
  • 10
  • 17