0

我有以下功能:

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

由此图像控件的可见属性调用:

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

无论我为该If IsDBNull部分尝试什么,它要么忽略它并执行代码,要么返回错误,例如Conversion from type 'DBNull' to type 'String' is not valid.

我该如何纠正这种情况?

4

3 回答 3

2

你在第一个 if 检查中有一个逻辑错误。

Not Nothing总是评估为真。所以第一条语句基本上可以编译为:

If IsDBNull(path) Or True Then

这将永远是真的。您的 if 语句应该如下所示:

If Not IsDBNull(path) And path Is Not Nothing Then
于 2013-01-26T01:16:05.197 回答
1

我不知道你为什么同时使用IsDBNulland Nothing,无论如何

使用AndAlso,如果 previous 为 false 则不会检查下一部分

首先检查路径以防止异常:

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

仅供参考, OrElse 将为 执行相同的功能Or,对我而言,我默认使用此短路逻辑运算符,请在此处阅读我的问题

于 2013-01-26T01:33:53.663 回答
0

利用

If Not String.IsNullOrEmpty(path) Then

因为您需要处理空字符串。您应该传递一个字符串,而不是一个通用对象。另外,你不能这样做Or Not Nothing。你必须这样做Not IsDBNull(path) And Not path Is Nothing

于 2013-01-26T01:50:25.707 回答