Loading image from database to picturebox - sql

I'm new to visual basic and I have a problem in loading the image from my database. I'm currently using image data type. This is how I save the image
Imports System.Data
Imports System.Data.SqlClient
Public Class ScannerX_Add
Dim ImageFilename As String
Dim ImageUpload As Image
Private Sub ButtonX1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Scan.Click
Try
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:\Users\ITTestServer\Desktop\Dekstop\"
OpenFileDialog1.ShowDialog()
ScannerX_Pic.Image = Image.FromFile(OpenFileDialog1.FileName)
ImageFilename = OpenFileDialog1.FileName
ImageUpload = Image.FromFile(OpenFileDialog1.FileName)
Catch ex As Exception
MsgBox("Please insert scan finger")
Exit Sub
End Try
End Sub
Private Sub Btn_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Save.Click
If ImageFilename <> "" Then
Dim imageNameTemp As String
imageNameTemp = ImageFilename
While (imageNameTemp.Contains("\"))
imageNameTemp = imageNameTemp.Remove(0, imageNameTemp.IndexOf("\") + 1)
End While
Dim ms As New IO.MemoryStream
If ImageFilename.Contains("jpeg") Or ImageFilename.Contains("jpg") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
If ImageFilename.Contains("png") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End If
If ImageFilename.Contains("gif") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
End If
If ImageFilename.Contains("bmp") Then
ImageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
End If
Dim b() As Byte = ms.ToArray()
Dim cmd As New SqlCommand("Insert into Scanner (Name,Finger) VALUES('" & TxtBox_Name.Text.Trim & "','" & imageNameTemp & "')", Connection)
cmd.Parameters.Add("#BLOBData", SqlDbType.Image, b.Length).Value = b
cmd.ExecuteNonQuery()
MsgBox("Profile Has Been Saved")
Me.Close()
End If
End Sub
Now I need to load my image to picturebox which is currently in the Main form.
Private Sub ButtonX1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonX1.Click
Command.CommandText = ("select Finger FROM Scanner")
Command.Connection = Connection
Dim da As New SqlDataAdapter(Command)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
Dim bytBLOBData() As Byte = _
ds.Tables(0).Rows(c - 1)("imagedate")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
ScannerX_Pic2.Image = Image.FromStream(stmBLOBData)
End If
End Sub
Now I get the error Object reference not set to an instance of an object.

To save an image you could do something like this
Dim sql As String = "INSERT INTO Information VALUES(#name,#photo)"
Image Img = PictureBox1.BackgroundImage
Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim ms As New MemoryStream()
Img.Save(ms, Img.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#photo", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
And to retrieve an image
cmd = New SqlCommand("select photo from Information where name='Rose'", con)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
Also check out this article it's doing exactly what you are trying to achieve
http://www.codeproject.com/Articles/437937/Save-and-Retrieve-Image-from-a-SQL-Server-Database

The sql is selecting a column named "Finger":
"select Finger FROM Scanner"
But it's later trying to build an Image object from a column named "imagedate":
ds.Tables(0).Rows(c - 1)("imagedate")
It needs to use the same column name as the SQL result set:
ds.Tables(0).Rows(c - 1)("Finger")
There may be other problems as well, but that's what jumped out at me right away.

Related

Get Image from SQL using Listbox to picturebox VB

i'm trying to get the image from SQL to picturebox using Listbox in in VB.
here is my sql sample table.
and here is my VB Design form, so what I'm trying to do is when I load the form, if an item in the listbox is selected, i want it to get the image(Binary Data) from sql to picturebox in vb net.
and the code I'm working with it give me this error:
VB full code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connect()
Dim co As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True")
co.Open()
Dim com As New SqlCommand("SELECT Image from Items where ItemName = '" & ListBox1.SelectedIndex & "'", co)
Dim img As Byte() = DirectCast(com.ExecuteScalar(), Byte())
Dim ms As MemoryStream = New MemoryStream(img)
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
PictureBox1.Image = Image.FromStream(ms)
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Remove the picture retrieval from the Form.Load. We have selected all the data in the GetDataFromSql function. The magic happens in the ListBox1.SelectedIndexChanged method.
The SelectedIndexChanged will occur as a result of the code in the Form.Load and every time the selection changes. When we bind the the list box to to binding source the entire row is added as a DataRowView. We can use this to get the data in the Image column. First check if the field is null. Next cast to a byte array. Take the byte array and pass it to the constructor of a MemoryStream. Streams need to be disposed so it is in a Using block. Finally the stream can be assigned to the Image property of the PictureBox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Image") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Image"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
EDIT
I switched the code over to a database I have available for testing. Even though it is not your database, I am sure you will be able to follow the code.
Here is the schema of my database.
The main difference is I moved the DataTable to a class level variable so it can be seen from all methods. I changed the GetDataFromSql to a Sub. It adds the data to the class level DataTable (Bounddt). The AddItem method first gets the Byte() from a file. The row is added to the DataTable with an Object array with elements that match the DataTable.
Private Bounddt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = Bounddt
ListBox1.DisplayMember = "CustomerID"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "CustomerID")
TextBox2.DataBindings.Add("Text", BndSrc, "CustomerName")
End Sub
Private Sub GetDataFromSql()
Using connection As New SqlConnection("Data Source=****;Initial Catalog='Small Database';Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"),
cmd As New SqlCommand("select * FROM Sales.Customer", connection)
connection.Open()
Using reader = cmd.ExecuteReader
Bounddt.Load(reader)
End Using
End Using
'Return dt
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Picture") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Picture"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
Private Sub AddItem()
Dim picture = GetByteArr("C:\Users\maryo\OneDrive\Documents\Graphics\Animals\squirrel.png")
Bounddt.Rows.Add({5, "George", 74, 62, "George", picture})
End Sub
Private Function GetByteArr(path As String) As Byte()
Dim img = Image.FromFile(path)
Dim arr As Byte()
Dim imgFor As Imaging.ImageFormat
Dim extension = path.Substring(path.LastIndexOf(".") + 1)
'There is a longer list of formats available in ImageFormat
Select Case extension
Case "png"
imgFor = Imaging.ImageFormat.Png
Case "jpg", "jpeg"
imgFor = Imaging.ImageFormat.Jpeg
Case "bmp"
imgFor = Imaging.ImageFormat.Bmp
Case Else
MessageBox.Show("Not a valid image format")
Return Nothing
End Select
Using ms As New MemoryStream
img.Save(ms, imgFor)
arr = ms.ToArray
End Using
Return arr
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddItem()
End Sub
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Dim con As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
Dim da As SqlDataAdapter
Private Const cs As String = "ConnectionString"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("select * from [dbo].[Item_Details]", con)
rdr = cmd.ExecuteReader()
While rdr.Read
ListBox1.Items.Add(rdr(1))
End While
con.Close()
End Sub
Private Sub ListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseClick
Try
con = New SqlConnection(cs)
con.Open()
da = New SqlDataAdapter("Select * from Item_Details where itemname='" & ListBox1.SelectedItem.ToString() & "'", con)
Dim dt As New DataTable
da.Fill(dt)
For Each row As DataRow In dt.Rows
TextBox1.Text = row(0).ToString()
TextBox2.Text = row(1).ToString()
TextBox3.Text = row(2).ToString()
Dim data As Byte() = row(3)
Dim ms As New MemoryStream(data)
PictureBox1.Image = Image.FromStream(ms)
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

Vb.net cant save picture using the ms.access Database

Okay please forgive me if this sound annoying but i keep getting an error nullreference whenever im trying to input my data.. Im sorry if im doing this wrong This is my first time posting here :
Imports System.IO
Imports System.Data.OleDb
Public Class halaman_daftar_anggota
Dim Conn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim CMD As OleDbCommand
Dim bytimage As Byte()
Dim LokasiDB As String
Sub Koneksi()
LokasiDB = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=perpustakaan.accdb"
Conn = New OleDbConnection(LokasiDB)
If Conn.State = ConnectionState.Closed Then Conn.Open()
End Sub
Private Sub halaman_daftar_anggota_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Koneksi()
da = New OleDbDataAdapter("Select * from data_anggota", Conn)
ds = New DataSet
ds.Clear()
da.Fill(ds, "data_anggota")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dialog As OpenFileDialog = New OpenFileDialog()
dialog.Title = "Browse Foto"
dialog.Filter = "image files(*.png; *.bmp; *.jpg;*.jpeg; *.gif; |*.png; *.bmp; *.jpg;*.jpeg; *.gif;)"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(dialog.FileName)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim ms As New System.IO.MemoryStream
Dim bmpimage As New Bitmap(PictureBox1.Image)
bmpimage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
bytimage = ms.ToArray()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Call Koneksi()
Dim simpan As String = "INSERT INTO data_buku (nomor_induk,nama_siswa,kelas_siswa,foto) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "',#image)"
CMD.Parameters.AddWithValue("#image", bytimage) <-"Error object reference not set to an instance of an object"
CMD = New OleDbCommand(simpan, Conn)
CMD.ExecuteNonQuery()
MsgBox("Berhasil")
End Sub
End Class
Whenever im trying to save a picture.in my database j already set foto as ole object... Im sorry..

how to retrieve picture in picture box from SQL?

I am trying to add image with its filename and file path in picture box from SQL but i am getting error "unable to cast system.string to system.byte". how can i do this?
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim connection As New SqlConnection("server= .\SQLEXPRESS; database = billing software; integrated security=true")
Dim command As New SqlCommand("select * from stockimagedata where imageid = #imageid", connection)
command.Parameters.Add("#imageid", SqlDbType.Int).Value = TextBox4.Text
Dim table As New DataTable()
Dim adapter As New SqlDataAdapter(command)
adapter.Fill(table)
TextBox4.Text = table.Rows(0)(0).ToString()
TextBox3.Text = table.Rows(0)(1).ToString()
TextBox5.Text = table.Rows(0)(2).ToString()
Dim img() As Byte
img = table.Rows(0)(2)
Dim ms As New MemoryStream(img)
PictureBox1.Image = Image.FromStream(ms)
End Sub

Insert & Retrieve Image in Postgresql database form VBNet

I want to insert and retrieve image in Postgresql database from VB.net on button click event. My table has one column "image" with datatype bytea. I have written below code but not getting desired output:
'Insert
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
Dim image1 As Byte()
Dim FS As FileStream = New FileStream("C:\0.jpg", FileMode.Open, FileAccess.Read)
Dim BR As BinaryReader = New BinaryReader(FS)
Dim lg As Long = FS.Length
Dim length As Integer = Convert.ToInt32(lg)
image1 = BR.ReadBytes(length)
conn.Open()
Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(#image1)", conn)
'Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table1 values('" & timestamp & "','" & serialno & "','" & modelname & "','0','0','0','0','0','0','0','0','0','0','0','0')", conn)
Command.Parameters.Add(New NpgsqlParameter("#image1", NpgsqlTypes.NpgsqlDbType.Bytea))
Command.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
'retrieve
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Try
conn.Open()
Dim com As NpgsqlCommand = New NpgsqlCommand("select image from table2", conn)
Dim reader As NpgsqlDataReader = com.ExecuteReader()
Dim imageInBytes As Byte() = reader("image")
Dim memoryStream As System.IO.MemoryStream = _
New System.IO.MemoryStream(imageInBytes, False)
Dim image As System.Drawing.Image = _
System.Drawing.Image.FromStream(memoryStream)
image.Save("E:\image")
PictureBox6.Image = image
conn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
You need values in parameters in 'Insert'...Change this...
Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(#image1)", conn)
Command.Parameters.Add(New NpgsqlParameter("image1", NpgsqlTypes.NpgsqlDbType.Bytea))
For this...
Dim Command As NpgsqlCommand = New NpgsqlCommand("INSERT INTO table2 Values(:image1)", conn)
Dim param As NpgsqlParameter = New NpgsqlParameter("image1", NpgsqlTypes.NpgsqlDbType.Bytea)
param.Value = image1
Command.Parameters.Add(param)
And in 'Retrieve' you need take length before... Change this...
Dim imageInBytes As Byte() = reader("image")
Dim memoryStream As System.IO.MemoryStream = _
New System.IO.MemoryStream(imageInBytes, False)
Dim image As System.Drawing.Image = _
System.Drawing.Image.FromStream(memoryStream)
image.Save("E:\image")
PictureBox6.Image = image
For something similar to this...
Dim imageInBytes As Byte()
reader.Read()
' Retrieve the length of the necessary byte array.
Dim column as integer = reader.GetOrdinal("name_column")
Dim len As Long = reader.GetBytes(column, 0, Nothing, 0, 0)
' Create a buffer to hold the bytes, and then
' read the bytes from DataReader.
ReDim imageInBytes(CInt(len))
reader.GetBytes(column, 0, imageInBytes, 0, CInt(len))
PictureBox1.Image = New Bitmap(New MemoryStream(imageInBytes))

Uploading/Retrieving an image of any format into SQL server data through vb 2010

I want to upload an image to data base, I found lots of code over the internet but non of them worked for me. I am browsing images with button Browse of format(png, gif, jpeg and bmp) and after then I want to upload these types of images to the data base with button Save.
For retrieving them back i use another button load. Can you please guide me how would i do this.
This is my coding Tell me where am I wrong.
Imports System.Data.SqlClient
Imports System.IO
Imports System.Drawing.Image
Public Class Employee
Dim myImage As Image
Dim imgMemoryStream As IO.MemoryStream = New IO.MemoryStream()
Dim imgByteArray As Byte() = Nothing
Dim con As SqlConnection = New SqlConnection("Data Source=CILENTEYEZ-PC\CILENTEYEZ;Initial Catalog=Keeper;Integrated Security=True")
Dim cmd As SqlCommand
Dim myDA As SqlDataAdapter
Dim myDataSet As DataSet
Dim dr As SqlDataReader
' From Here This is the Code for Insertion.
Private Sub BrowsePic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowsePic.Click
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Select your Image."
fd.InitialDirectory = "C:\"
fd.Filter = "All Files|*.*|Bitmaps|*.bmp|GIFs|*.gif|JPEGs|*.jpg|PNGs|*.png"
fd.RestoreDirectory = False
If fd.ShowDialog() = DialogResult.OK Then
PictureBox.ImageLocation = fd.FileName
ElseIf fd.FileName.Contains("jpeg") Or fd.FileName.Contains("jpg") Then
myImage.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg)
imgByteArray = imgMemoryStream.GetBuffer()
ElseIf fd.FileName.Contains("png") Then
myImage.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Png)
imgByteArray = imgMemoryStream.GetBuffer()
ElseIf fd.FileName.Contains("gif") Then
myImage.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Gif)
imgByteArray = imgMemoryStream.GetBuffer()
ElseIf fd.FileName.Contains("bmp") Then
myImage.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Bmp)
imgByteArray = imgMemoryStream.GetBuffer()
End If
End Sub
Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
cmd = New SqlCommand("Insert Into Employee Values('" & SR_CodeTextBox.Text.Trim() & "','" & NameTextBox.Text.Trim() & "','" & CNICTextBox.Text.Trim() & "','" & Date_of_BirthDateTimePicker.Text & "','" & AgeTextBox.Text.Trim() & "','" & AddressTextBox.Text.Trim() & "',# imgByteArray ,'" & Mobile_NumberTextBox.Text.Trim() & "')", con)
If con.State = ConnectionState.Closed Then con.Open()
cmd.ExecuteNonQuery()
con.Close()
MessageBox.Show("New Employee Record is Added.", "Message", MessageBoxButtons.OK)
End Sub
' From Here This is the Code for Eiditing.
Private Sub Go_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Go.Click
cmd = New SqlCommand("Select * from Employee where SR_Code = '" & SearchBox.Text.Trim() & "'", con)
If SearchBox.Text = "" Then
MsgBox("Please enter SR Code first.")
Else
Try
If con.State = ConnectionState.Closed Then con.Open()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
Edit_SR_CodeTextBox.Text = dr.Item("SR_Code")
Edit_NameTextBox.Text = dr.Item("Name")
Edit_CNICTextBox.Text = dr.Item("CNIC")
Edit_Date_of_BirthDateTimePicker.Text = dr.Item("Date_of_Birth")
Edit_AgeTextBox.Text = dr.Item("Age")
Edit_AddressTextBox.Text = dr.Item("Address")
imgByteArray = dr.Item("Picture")
Edit_Mobile_NumberTextBox.Text = dr.Item("Mobile_Number")
imgMemoryStream = New IO.MemoryStream(imgByteArray)
myImage = Drawing.Image.FromStream(imgMemoryStream)
PictureBox.Image = myImage
MsgBox("Record Retrieved.")
con.Close()
ElseIf dr.Read = False Then
MsgBox("Please enter a valid SR Code to load data.")
con.Close()
End If
Catch ex As Exception
MessageBox.Show(ex, "Message")
End Try
End If
End Sub
For image browsing you can use this code.
Private Sub BrowsePic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowsePic.Click
Dim ImageDialogue As OpenFileDialog = New OpenFileDialog()
ImageDialogue.Title = "Select your Image."
ImageDialogue.InitialDirectory = "C:\"
ImageDialogue.Filter = "Image Files|*.gif;*.jpg;*.png;*.bmp;"
ImageDialogue.RestoreDirectory = False
If ImageDialogue.ShowDialog() = DialogResult.OK Then
PictureBox.Image = Image.FromFile(ImageDialogue.FileName)
End If
End Sub
For Image Uploading(into Database) you can use this code in VB 2010.
cmd = New SqlCommand("Insert Into Proposer Values(& #Picture )", con)
If con.State = ConnectionState.Closed Then con.Open()
Dim ms As New MemoryStream()
PictureBox.Image.Save(ms, PictureBox.Image.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#Picture", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
con.Close()
For Image retrieving(from Database) I used this Code in VB 2010.
Dim data As Byte() = DirectCast(dr("Picture"), Byte())
Dim ms As New MemoryStream(data)
Edt_PictureBox.Image = Image.FromStream(ms)
Note: This to be used in VB-2010 not tried on VB-2008. And As you see the code is a bit different from C#, so don't expect it to work on C#.
I you could make changes(mean conversion to C#) then it'll work.