Store Image into SQL Database using VB.Net
Here is the steps to save image into database.I'm using picture box to show saved image in database.
Before all this create one database, and one table with the name tbl_Employee and the following feilds
Field
Name
|
Data
Type
|
Empcode
|
int
|
Address
|
Varchar(500)
|
Password
|
Varchar(50)
|
Photo
|
image
|
Here is interface which is used in pick image from local
system. Having picture box and two button Add Photo, Remove Photo.
Here is code for Add Photo button.
Private Sub cmdAddPhoto_Click(ByVal
sender As System.Object, ByVal e As
System.EventArgs) Handles cmdAddPhoto.Click
If
dlgOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then
pic.Image =
Image.FromFile(dlgOpen.FileName)
picFlag = "edit"
End If
End Sub
and code for Remove Button.
Private Sub cmdRemPhoto_Click(ByVal
sender As System.Object, ByVal e As
System.EventArgs) Handles cmdRemPhoto.Click
If
MsgBox("Are you sure to remove agent
photo", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm?") = MsgBoxResult.No Then Exit Sub
pic.Image = My.Resources.noimage
picFlag = "edit"
End Sub
After coding all this we are going to code for save Button Event as Follow.This procedure takes image from PictureBox control named "pic" as a sql parameter.Here i use a function "ConvertImageToByte" for converting image to bytes. Dim
sqlConn As New
SqlClient.SqlConnection()
sqlConn.ConnectionString = "Password=123;Persist
Security Info=True;User ID=sa;Data Source=.;initial catalog=dbEmp"
Dim SqlCmd As
New SqlClient.SqlCommand
SqlCmd.Connection
= sqlConn
Sql = "insert into
tbl_Employee(Empcode,Address,Password,Photo) Values(" & _
"'"
& CStr(EmpCode.Text) & "'," & _
"'"
& CStr(Address.Text) & "'," & _
"'"
& CStr(Password.Text) & "'," & _
"'"
& Format(Now, "MM/dd/yyyy")
& "'," & _
"@pics)"
SqlCmd.CommandText = Sql
Dim
picphoto As New
SqlClient.SqlParameter("@pics",
SqlDbType.Image)
picphoto.Value =
ConvertImageToByte(pic.Image)
SqlCmd.Parameters.Add(picphoto)
Dim c As Integer =
SqlCmd.ExecuteNonQuery()
If c <> 0 Then
MsgBox("Record Saved Successfully.",
MsgBoxStyle.Information, "Message")
End If
After successfully saving image into database it will give message for confirmation.
Comments
Post a Comment