GridView with an empty image handler returns an error RRS feed

  • Question

  • User17798125 posted

    Hi forum,

    I have a gridview that holds an image, but when I click my button to try to find all my info, an error returns with the next error:
    System.InvalidCastException: 'No se puede convertir un objeto de tipo 'System.DBNull' al tipo 'System.Byte[]'.' 

    My WebHandler is this, and the debugger points to the line in yellow.

    <%@ WebHandler Language="VB" Class="Handler" %>
    Imports System.Web
    Imports System.Configuration
    Imports System.Data.SqlClient
    Public Class Handler
        Implements IHttpHandler
        Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            Dim imageid As String = context.Request.QueryString("ImID")
            Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("std").ConnectionString)
            Dim command As New SqlCommand("select img from stdplusreport1 where ImageID=" & imageid, connection)
            Dim dr As SqlDataReader = command.ExecuteReader()
            context.Response.BinaryWrite(DirectCast(dr(0), [Byte]()))
        End Sub
        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
                Return False
            End Get
        End Property
    End Class

    I have tried to convert pass to the null what is null, like the next but without success, I cannot find the the correct sentence.

    If dr.Read() Then
    context.Response.BinaryWrite(DirectCast(dr(0), [Byte]()))
    End If

    Any Ideas? 
    Thanks! In advance!

    Friday, February 15, 2019 12:14 AM

All replies

  • User-1716253493 posted

    Before casting, chek

            If Not IsDBNull(dr(0)) Then
            End If

    another option

    Dim command As New SqlCommand("select img from stdplusreport1 where not img is null 
    and ImageID=" & imageid, connection)

    Friday, February 15, 2019 1:14 AM
  • User17798125 posted


    Thanks, but it did not work… Any other suggestions?

    Friday, February 15, 2019 5:37 AM
  • User-1174608757 posted

    Hi Jonsry10

    According to your description,it seems that the data of sqldataReader exists null data.So, I suggest you to use reader.HasRows to check whether the row  exists

    You could write as below:

    Dim dr As SqlDataReader = Command.ExecuteReader()
                If dr.HasRows Then
                    While dr.Read()
                        Context.Response.BinaryWrite(DirectCast(dr(0), [Byte]()))
                    End While
                End If

    Best Regards

    Wei Zhang

    Monday, February 18, 2019 7:01 AM