开发者

What is wrong with this null check for data reader

            c.Open()
            r = x.ExecuteReader
            If Not r("filename").IsDbnull Then
                imagepath = "<img src='images/'" & getimage(r("filename")) & " border='0' align='absmiddle'"

            End If
            c.Close()
            r.Close()

I have also tried;

If r("filename") Is DBNull.Value Then
            imagepath = String.Empty
        Else
            imagepath = "<img src='images/'" & getimage(r("filename")) & " border='0' align='absmiddle'"
        End If
        c.Close()
        r.Close()

The error is: Invalid attempt to read when no data is present.

The idea of my code is to build an img src string only when data is available.

Help greatly appreciated.

开发者_如何转开发

Thanks


You need to call the Read method on your SqlDataReader before data is available for reading.

r = x.ExecuteReader
r.Read()


The Read method needs to be called first.

If r.Read() AndAlso Not r("filename").IsDbnull Then ...


If there are 0 rows in the DataReader after the query is run, there will be no fields at all so you can't compare them to null.

You can check for this with if r.HasRows then //got data ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜