load SQL database image into picturebox


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

Who is Participating?
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

michaelhendersonAuthor Commented:
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.
michaelhendersonAuthor Commented:
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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

michaelhendersonAuthor Commented:
I want to cancel this close as I wanted to accept the solution (not my own comment)
michaelhendersonAuthor Commented:
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
How to close it without any points,
I gave an answer and I should get at least some points

michaelhendersonAuthor Commented:
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!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.