How to Retrieve an Image in MySQL Database Using VB.Net

This tutorial is the continuation of my last tutorial which is How to Save Image In MySQL Database Using VB.Net. This time I’m going to teach you how to Retrieve Image in MySQL Database Using VB.Net. In this method, it will retrieve the image or file from the MySQL database into the picturebox.. Lets begin: Open the Project that you have created in the previous tutorial then add the button in the form just like shown below. ps_1 Add another Form in the project and do the form just like this. ps_2 double click the second Form to fire the code view. In the code view add Imports MySql.Data.MySqlClient and Imports System.IO above the Public Class for you imports. Go back to the design view, click the Retrieve button inside the second form to open the click event handler of it. After that do the following code for retrieving data from MySQL database into the datagridview.
  1. Try
  2. con.Open()
  3. cmd = New MySqlCommand
  4. With cmd
  5. .Connection = con
  6. .CommandText = "SELECT ImageID,Caption FROM tblimageblob"
  7. End With
  8. da = New MySqlDataAdapter
  9. da.SelectCommand = cmd
  10. dt = New DataTable
  11. da.Fill(dt)
  12.  
  13. With dtglist
  14. .DataSource = dt
  15. End With
  16.  
  17. Catch ex As Exception
  18. MsgBox(ex.Message)
  19. Finally
  20. da.Dispose()
  21. con.Close()
  22. End Try
Go back to the design view again and double click the View Image button open the click event handler of it. Do the following code for retrieving image in the picture box.
  1.  
  2. Try
  3. con.Open()
  4. cmd = New MySqlCommand
  5. With cmd
  6. .Connection = con
  7. .CommandText = "SELECT Caption,ImageFile FROM tblimageblob WHERE ImageID=" & Val(dtglist.CurrentRow.Cells(0).FormattedValue)
  8. End With
  9. da = New MySqlDataAdapter
  10. dt = New DataTable
  11. Dim arrImage() As Byte
  12.  
  13. da.SelectCommand = cmd
  14. da.Fill(dt)
  15.  
  16. txtCaption.Text = dt.Rows(0).Item(0)
  17. arrImage = dt.Rows(0).Item(1)
  18. Dim mstream As New System.IO.MemoryStream(arrImage)
  19. PictureBox1.Image = Image.FromStream(mstream)
  20.  
  21. Catch ex As Exception
  22. MsgBox(ex.Message)
  23. Finally
  24. da.Dispose()
  25. con.Close()
  26. End Try
Output ps_3

Comments

Submitted byMateusz (not verified)on Sun, 02/09/2020 - 04:33

Hello! Could you explain what is da, dt and dtglist in your code? I guess i need declaration for them.
Submitted byinfocodtech (not verified)on Sat, 02/13/2021 - 00:30

In reply to by Mateusz (not verified)

Hi! da is Data Adapter dt is Data Table dtglist is DatagridList also known as Datagridview tool.

Add new comment