
Originally Posted by
itpccc
How do I Add photo records in sql through VB .net
Code:
'1. create field(of type image) in sql server for the photo
'2.'bind the picture to a picture box on the form load event
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
''' Add bindings for the picture box
Dim b As Binding = New Binding("Image", mydataset, "tblCompanyInfo.Logo")
AddHandler b.Format, AddressOf ConvertPicture
Me.PictureBoxLogo.DataBindings.Add(b)
Me.PictureBoxLogo.SizeMode = PictureBoxSizeMode.StretchImage
Me.PictureBoxLogo.ClientSize = New Size(112, 104)
'''
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error Binding Picture")
End Try
Catch expSQL As SqlException
MessageBox.Show(expSQL.ToString, Me.Text, _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
End Sub
Private Sub ConvertPicture(ByVal sender As System.Object, ByVal e As ConvertEventArgs)
'converts a byte array to image
If Not e.Value Is DBNull.Value Then
Dim b() As Byte
b = e.Value
Dim ms As MemoryStream = New MemoryStream
ms.Write(b, 0, b.Length)
Dim bmp As Bitmap = New Bitmap(ms)
ms.Close()
e.Value = bmp
Else
'an error will occur if you dont supply some form of dummy picture
'therefore create a blank picture for the initial startup
'then you can repalce it with anyone you like
If File.Exists(Application.StartupPath & "\Blank.jpg") Then
Dim bmp As Bitmap = New Bitmap(Application.StartupPath & "\Blank.jpg")
e.Value = bmp
Else
MsgBox(Application.StartupPath & "\Blank.jpg Is Missing", MsgBoxStyle.Critical, "Error")
End If
End If
End Sub
'3.Convert the picture to binary and save it to the database
'convert the picture to binary for storage
If File.Exists(Me.txtLogo.Text) Then
Dim fs As New FileStream(Me.txtLogo.Text, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fs)
Dim row As DataRow
row = mydataset.Tables(0).Rows(0)
row.BeginEdit()
row("logo") = br.ReadBytes(br.BaseStream.Length)
row.EndEdit()
br.Close()
fs.Close()
br = Nothing
fs = Nothing
End If
mybmb.EndCurrentEdit()
mydataAdapter.Update(mydataset, "tblCompanyInfo")
MsgBox("The Information Was Sucessfully Updated", MsgBoxStyle.Information, "Information")