load SQL database image into picturebox

Posted on 2011-10-12
Last Modified: 2012-05-12

I’m having trouble reading an image from my database table (stored as file type image).

I’ve searched the net for advice for what I presumed would be a very common thing but I’m having trouble finding the relevant code.

Basically, I have a form which reads an SQL asset database table and displays the matching contents in various controls.  

I have an option of clicking a browse button which allows the user to search for an image.  When they click the save button, the image path and filename gets stored in my table as well as the image itself. This works fine.

My issue is that when I read this table, I cannot load the matching image and put it in a picture box.  I get the following error:

“Conversion from type ‘Byte()’ to type ‘Byte’ is not valid”

Here’s my code to load the data (image loading at the bottom.)

Private Sub loadData()
        Dim connection As New SqlConnection(ConnectionString)
        Dim DataSet As New DataSet
        Dim valueArray As Byte = Nothing

        stringQuery = "SELECT PartNo_AssetID AS [Asset], AssetType AS [Asset Type], AssetTypeID, NoOfImpressions AS [Number Of Impresions], DateT1, Date, CompletedBy AS [Completed By], Location, PartDescription AS [Part Description], SupplierToolNo AS [Supplier Tool Number], VolumePerAnnum AS [Volume Per Annum], PurchasePrice as [Purchase Price], DrawingIssueLevel AS [Drawing Issue Level], DraegerAssetNo AS [Draeger Asset Number], AssetImage, ImageFileName, VendorCode AS [Vendor Code], Asset.CompanyID, CompanyName AS [Company Name] FROM Asset INNER JOIN AssetType ON Asset.AssetTypeID = AssetType.ID INNER JOIN Company ON Asset.CompanyID = Company.CompanyID WHERE PartNo_AssetID = '" & varID & "' ORDER BY [Asset]"
        With ToolStripLabelAsset
            .Text = varID
        End With

        Dim DataAdapter As New SqlDataAdapter(stringQuery, connection)



        Dim Table As DataTable = DataSet.Tables(0)

            If Table.Rows.Count = 0 Then
                popupMessageHandler("There are no records to display")
                cboVendorCode.Text = Table.Rows(0).Item("Vendor Code").ToString
                cboCompany.Text = Table.Rows(0).Item("Company Name").ToString
                txtPartNumber.Text = Table.Rows(0).Item("Asset").ToString
                cboAssetType.Text = Table.Rows(0).Item("Asset Type").ToString
                txtNoofImpressions.Text = Table.Rows(0).Item("Number Of Impresions").ToString
                DTDateT1.Value = Mid(Table.Rows(0).Item("DateT1"), 1, 10).ToString
                txtPartDescription.Text = Table.Rows(0).Item("Part Description").ToString
                txtCompletedBy.Text = Table.Rows(0).Item("Completed By").ToString
                DTDate.Value = Mid(Table.Rows(0).Item("Date"), 1, 10).ToString
                txtLocation.Text = Table.Rows(0).Item("Location").ToString
                txtSupplierToolNo.Text = Table.Rows(0).Item("Supplier Tool Number").ToString
                txtVolumePerAnnum.Text = Table.Rows(0).Item("Volume Per Annum").ToString
                txtPurchasePrice.Text = Table.Rows(0).Item("Purchase Price").ToString
                txtDrawingIssueLevel.Text = Table.Rows(0).Item("Drawing Issue Level").ToString
                txtDraegerAssetNo.Text = Table.Rows(0).Item("Draeger Asset Number").ToString
                varCompanyID = Table.Rows(0).Item("AssetTypeID").ToString
                varAssetTypeID = Table.Rows(0).Item("CompanyID").ToString
                lblFilePath.Text = Table.Rows(0).Item("ImageFileName").ToString

                'image ***** NOT WORKING
                valueArray = (Table.Rows(0).Item("AssetImage"))
                Dim ms As MemoryStream = New MemoryStream(valueArray)
                pbAssetImage.Image = New Bitmap(ms)
            End If

        Catch ex As Exception
            popupMessageHandler(Me.Name & " - loadData() - " & ex.Message)
        End Try
    End Sub

Open in new window

I’ve also included the save image code which works to give an idea of how the image is stored in the database.

Private Sub btnSaveImage_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveImage.Click
        Dim connection As New SqlConnection(ConnectionString)
        Dim arrFilename() As String = Split(lblFilePath.Text, "\")


        Dim ms As New MemoryStream
        pbAssetImage.Image.Save(ms, pbAssetImage.Image.RawFormat)
        Dim arrImage() As Byte = ms.GetBuffer


        Dim isConnecting As Boolean = True
        While isConnecting

                Dim myConnection As New SqlConnection(ConnectionString)
                Dim SQL As String = "UPDATE Asset SET ImageFileName = '" & lblFilePath.Text & "', AssetImage = '@Picture' WHERE (PartNo_AssetID = '" & varID & "')"

                Dim myCommand As New SqlCommand(SQL, myConnection)
                With myCommand
                    .Parameters.Add(New SqlParameter("@Filename", SqlDbType.NVarChar, 50)).Value = arrFilename(0)
                    .Parameters.Add(New SqlParameter("@Picture", SqlDbType.Image)).Value = arrImage
                End With




                isConnecting = False
                didPreviouslyConnect = True
                MessageBox.Show(arrFilename(0) & " Saved To The Database.", "Image Save Status", MessageBoxButtons.OK, MessageBoxIcon.Information)

            Catch sqlExc As SqlException
                MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit While

            Catch exc As Exception
            End Try
        End While
    End Sub

Open in new window

Question by:michaelhenderson
    LVL 2

    Accepted Solution

    you can use the following code:

    Dim bits As Byte() = CType(Table.Rows(0).Item("AssetImage"), Byte())
                                Dim memoryBits As New MemoryStream(bits)
                                Dim bitmap As New Bitmap(memoryBits) 'bitmap has the image now.
                                pbAssetImage.Image = bitmap

    Open in new window


    Author Comment

    Thanks for the help.  I've tried your code which looks more like what I was after!  

    I'm now getting a "parameter is not valid" error message.  I'll have a search on that error.

    Author Comment

    I've requested that this question be closed as follows:

    Accepted answer: 0 points for michaelhenderson's comment http:/Q_27392497.html#36954907

    for the following reason:

    I've modified the code a little:<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Dim bits As Byte() = CType(Table.Rows(0).Item(&quot;<wbr />AssetImage<wbr />&quot;), Byte())<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Dim memoryBits As New MemoryStream(bits)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Dim imgBitmap As New Bitmap(memoryBits) 'bitmap has the image now.<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Dim imgBitmap As New Bitmap(Table.Rows(0).Item(<wbr />&quot;ImageFile<wbr />Name&quot;).ToS<wbr />tring())<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pbAssetImage.Image = imgBitmap<br /><br />The parameter it was looking for was the filename &amp; path. &nbsp;I had this stored anyway. &nbsp;The only issue is I was hoping the image would be embeded so if the picture was deleted from a drive, it would still be able to be displayed. &nbsp;I have now added code to check that the file exists first and if not, it displays a generic image instead of the saved one.<br /><br />Thanks for the help

    Author Comment

    I want to cancel this close as I wanted to accept the solution (not my own comment)

    Author Comment

    Don't know what's going on with this but I'd like to accept the code from Jassimi: as a partial complete.

    I had to modify the code a little but it gave me a good pointer to the problem.  

    The parameter it was looking for was the filename & path.  I had this stored anyway.  The only issue is I was hoping the image would be embeded so if the picture was deleted from a drive, it would still be able to be displayed.  I have now added code to check that the file exists first and if not, it displays a generic image instead of the saved one.

    Thanks for the help
    LVL 2

    Expert Comment

    How to close it without any points,
    I gave an answer and I should get at least some points


    Author Closing Comment

    I agree, I wanted to award you points (and I'm still trying) but the solution I accepted was my own comment by mistake and I'm struggling to give you the points that i'd like to!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    PRTG Network Monitor: Intuitive Network Monitoring

    Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

    Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
    INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now