-2

I am having issues assigning an image to every button according to my database.

My current code:

 Dim strsql As String
 Dim ImgSQl As Image

 Dim con As New SqlConnection("constring")
 con.Open()

 strsql = "SELECT Image FROM Inventory WHERE ID=@ID"

 Dim cmd As New SqlCommand(strsql, con)

 ItemID = 1
 cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ItemID
 Dim myreader As SqlDataReader
    
 myreader = cmd.ExecuteReader
 myreader.Read()
 ImgSQl = myreader("Image")
 con.Close()

 btn1.Image = ImgSQl

This is the error I'm getting:

Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jumexmango
  • 53
  • 7
  • 3
    Does this answer your question? [Byte array to image conversion](https://stackoverflow.com/questions/9173904/byte-array-to-image-conversion) – GSerg Sep 27 '21 at 16:56
  • 1
    @jumexmango In answers to previous questions of yours, there were details about `Using` for SqlClient objects, but you're still using `Dim` in this latest question. – HardCode Sep 27 '21 at 19:50
  • @HardCode That's true, I will change `Dim con` to `Using con` for this. Thank you. – jumexmango Sep 27 '21 at 20:00

1 Answers1

0

All I had to do was dim as Byte, also adding "()" is really important for it to work. Hope answering my own question helps a VB.net beginner out there.

   Dim strsql As String
   Dim ImgSql() As Byte
    
     Using con As New SqlConnection("constring")
     con.Open()
    
     strsql = "SELECT Image FROM Inventory WHERE ID=@ID"
    
     Dim cmd As New SqlCommand(strsql, con)
    
     ItemID = 1
     cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ItemID
     Dim myreader As SqlDataReader
        
     myreader = cmd.ExecuteReader
     myreader.Read()
     ImgSql = myreader("Imagen")
     Dim ms As New MemoryStream(ImgSql)
     btn1.Image = Image.FromStream(ms)
     con.Close()
    End Using
    
jumexmango
  • 53
  • 7
  • 1
    Connections are precious resources. Please don't open a connection until directly before the command is executed. DataReaders also need to be disposed so, add a Using block for your reader. Just noticed that you have failed to put your command in a Using also. – Mary Sep 28 '21 at 23:59
  • 1
    You don't have to close you connection. The End Using will handle that for you. – Mary Sep 29 '21 at 00:00
  • @Mary I will start placing my connections better. Thank you for sharing your knowledge. – jumexmango Sep 29 '21 at 16:06
  • You can create the connection object just as you have done. Just don't call the `Open` method until just before the `Execute...`. – Mary Sep 29 '21 at 16:15