?
Solved

load SQL database image into picturebox

Posted on 2011-10-12
8
Medium Priority
?
530 Views
Last Modified: 2012-05-12
Hi

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

        connection.Open()
        Dim DataAdapter As New SqlDataAdapter(stringQuery, connection)

        DataAdapter.Fill(DataSet)

        DataAdapter.Dispose()
        connection.Close()

        Dim Table As DataTable = DataSet.Tables(0)

        Try
            If Table.Rows.Count = 0 Then
                popupMessageHandler("There are no records to display")
            Else
                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, "\")

        Array.Reverse(arrFilename)

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

        ms.Close()

        Dim isConnecting As Boolean = True
        While isConnecting

            Try
                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

                myCommand.Connection.Open()
                myCommand.ExecuteNonQuery()

                myCommand.Connection.Close()

                connection.Close()

                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
            End Try
        End While
    End Sub

Open in new window

0
Comment
Question by:michaelhenderson
  • 5
  • 2
7 Comments
 
LVL 2

Accepted Solution

by:
Jassimi earned 375 total points
ID: 36954788
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

0
 

Author Comment

by:michaelhenderson
ID: 36954907
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.
0
 

Author Comment

by:michaelhenderson
ID: 36961221
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
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:michaelhenderson
ID: 36955352
I want to cancel this close as I wanted to accept the solution (not my own comment)
0
 

Author Comment

by:michaelhenderson
ID: 36955381
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
0
 
LVL 2

Expert Comment

by:Jassimi
ID: 36961222
How to close it without any points,
I gave an answer and I should get at least some points

thanks
Jassimi
0
 

Author Closing Comment

by:michaelhenderson
ID: 36967763
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!
0

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

862 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