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

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.

Related

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..

Import and Export csv File from DataGridView

High there, I'm currently making a small piece of software for a college project, The goal of the project is for the user to import ingredients and infomration and then they can create meals with these ingredients.
I'm having an issue though where when I load my csv file in after I've used the software once to add in a new ingredient I get the error: "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" and it highlights the section of the code "newRow("Protien") = columns(1)" Now I think is because when it loads in the data from the recently saved csv file it has a row at the top that is filled with the headers, is there any way that I can save the csv file without including the headers from the data table?
Code that laods in the csv file:
'Sets up the data table that will be used to store the ingredients and their information.'
With ingredientTable
.Columns.Add("Name", System.Type.GetType("System.String"))
.Columns.Add("Protien", System.Type.GetType("System.Decimal"))
.Columns.Add("Fat", System.Type.GetType("System.Decimal"))
.Columns.Add("Salt", System.Type.GetType("System.Decimal"))
.Columns.Add("Carbs", System.Type.GetType("System.Decimal"))
.Columns.Add("Calories", System.Type.GetType("System.Decimal"))
End With
'Loads in the information from the CSV file to display all the previouly saved ingredients'
Dim fileReader As New IO.StreamReader("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", System.Text.Encoding.Default)
Dim ingredientString As String = ""
Do
ingredientString = fileReader.ReadLine
If ingredientString Is Nothing Then Exit Do
'Reads what is on the CSV file and sets up the columns and the rows.'
Dim columns() As String = ingredientString.Split(",")
Dim newRow As DataRow = ingredientTable.NewRow
newRow("Name") = columns(0)
newRow("Protien") = columns(1)
newRow("Fat") = columns(2)
newRow("Salt") = columns(3)
newRow("Carbs") = columns(4)
newRow("Calories") = columns(5)
ingredientTable.Rows.Add(newRow)
Loop
fileReader.Close()
DataGridView1.DataSource = ingredientTable
Me.Text = ingredientTable.Rows.Count & "rows"
Code that saves the CSV file:
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
#Region "Save ingredients"
Dim csvFile As String = String.Empty
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
'Used to ge the rows
For Each row As DataGridViewRow In DataGridView1.Rows
'Used to get each cell in the row
For Each cell As DataGridViewCell In row.Cells
csvFile = csvFile & cell.FormattedValue & ","
Next
csvFile = csvFile.TrimEnd(",")
csvFile = csvFile & vbCr & vbCrLf
Next
My.Computer.FileSystem.WriteAllText("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", csvFile, False)
#End Region
Here are a few options to consider, for loading data from a CSV to a DGV.
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Dim str As String = ""
Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
sw.WriteLine(String.Join(",", headers))
'sw.WriteLine(String.Join(","))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
sw.Close()
End Using
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"
'Catch ex As Exception
' MessageBox.Show(ex.ToString())
'End Try
'Dim objDataset1 As DataSet()
'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Dim da As OdbcDataAdapter
Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
Dim strFullPath As String, strFileName As String
Dim tbFile As New TextBox
' Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box
If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
strFullPath = OpenFile.FileName ' Assigns variable
strFileName = Path.GetFileName(strFullPath)
If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file
tbFile.Text = strFullPath ' Puts the filename in the textbox
' The connection string for reading into data connection form
Dim connStr As String
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "
' Sets up the data set and gets stuff from .csv file
Dim Conn As New OdbcConnection(connStr)
Dim ds As DataSet
Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
ds = New DataSet
Try
DataAdapter.Fill(ds, strFileName) ' Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source
' Catch and display database errors
Catch ex As OdbcException
Dim odbcError As OdbcError
For Each odbcError In ex.Errors
MessageBox.Show(ex.Message)
Next
End Try
' Cleanup
OpenFile.Dispose()
Conn.Dispose()
DataAdapter.Dispose()
ds.Dispose()
End If
End If
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim tblReadCSV As New DataTable()
tblReadCSV.Columns.Add("FName")
tblReadCSV.Columns.Add("LName")
tblReadCSV.Columns.Add("Department")
Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")
csvParser.Delimiters = New String() {","}
csvParser.TrimWhiteSpace = True
csvParser.ReadLine()
While Not (csvParser.EndOfData = True)
tblReadCSV.Rows.Add(csvParser.ReadFields())
End While
Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
Dim strSql As String = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)"
'Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Connection = con
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName")
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName")
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department")
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
Dim result As Integer = dAdapter.Update(tblReadCSV)
End Sub
End Class
You must try this code.
OpenButton
Dim OpenFileDialog1 As New OpenFileDialog()
Dim constr As String
Dim con As OleDb.OleDbConnection
Try
OpenFileDialog1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm;"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Me.txtOpen.Text = OpenFileDialog1.FileName
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDb.OleDbConnection(constr)
con.Open()
cboSheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
cboSheet.DisplayMember = "TABLE_NAME"
cboSheet.ValueMember = "TABLE_NAME"
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Load Button
Dim constr As String
Dim dt As DataTable
Dim con As OleDbConnection
Dim sda As OleDbDataAdapter
Dim row As DataRow
Try
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
con = New OleDbConnection(constr)
sda = New OleDbDataAdapter("Select * from [" + cboSheet.SelectedValue + "]", con)
dt = New DataTable
sda.Fill(dt)
For Each row In dt.Rows
DataGridView3.DataSource = dt
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I hope it will works! :)

Loading image from database to picturebox

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.

How to insert, edit, delete image in SQL using vb.net

I can't Search and Edit using this Code. Insert is working. But Insert coding method is not sure (fileContent.ToString). And Search part and Update part is not working.
Dim fileContent As Byte() = My.Computer.FileSystem.ReadAllBytes(OpenFileDialog1.FileName)
Sub NormalUpdate(ByVal _Query)
con.Open()
Dim cmdUpdate As New SqlCommand(_Query)
cmdUpdate.Connection = con
cmdUpdate.CommandType = CommandType.Text
cmdUpdate.ExecuteNonQuery()
con.Close()
End Sub
Sub NormalSave(ByVal _Query)
con.Open()
Dim cmdSave As New SqlCommand(_Query)
cmdSave.Connection = con
cmdSave.CommandType = CommandType.Text
cmdSave.ExecuteNonQuery()
con.Close()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
NormalSave("Insert into Registration values('" + txtMemberNo.Text + "','" + fileContent.ToString + "')")
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
Using cmd As New SqlClient.SqlCommand("Select MemberPicture From Registration where MemberNo = '" + txtMemberNo.Text + "'", con)
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
Using dt As New DataTable
dt.Load(dr)
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row("MemberPicture"), Byte()))
Dim img As Image = Image.FromStream(ms)
ProfilePic.Image = img
con.Close()
End Using
End Using
End Using
End Using
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
NormalUpdate("Update Registration set MemberPicture = '" + fileContent.ToString + "' where MemberNo = '" + txtMemberNo.Text + "'")
End Sub
Please help me. Thanks.
Not sure if this is what you are looking for, but I use the following to get and set images from a database:
Public Function GetClientImage(ID As String) As Image
Dim ClientPicture As Image = Nothing
Dim DS As DataSet = Nothing
'Populate DS here
If (DS IsNot Nothing) AndAlso (DS.Tables.Count > 0) AndAlso (DS.Tables(0).Rows.Count > 0) Then
Dim DR As DataRow = DS.Tables(0).Rows(0)
Try
Dim Pic As Object = DR!Picture
If Pic IsNot DBNull.Value Then
Dim Buffer As Byte() = CType(DR!Picture, Byte())
If Buffer IsNot Nothing AndAlso (Buffer.Length > 0) Then
Using MS As New IO.MemoryStream(Buffer, 0, Buffer.Length)
MS.Write(Buffer, 0, Buffer.Length)
ClientPicture = Image.FromStream(MS, True)
End Using
End If
End If
Catch ex As Exception
MessageBox.Show("Error retrieving Image: " & ControlChars.NewLine & ControlChars.NewLine & ex.ToString, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End If
Return ClientPicture
End Function
and:
Public Function UpdateClientImage(ID As String, Pic As Image) As Integer
Dim Result As Integer = 0
If Client IsNot Nothing Then
Dim SQL As String = "UPDATE Clients SET Picture = #photo WHERE ID = '" & ID & "' ;"
Using SQLConn As New SqlClient.SqlConnection(ConnectionString)
Try
SQLConn.Open()
Using SQLCmd As New SqlClient.SqlCommand(SQL, SQLConn)
Dim PhotoParameter As New SqlClient.SqlParameter("#photo", SqlDbType.Image)
Dim MS As New IO.MemoryStream()
If Pic IsNot Nothing Then
Pic.Save(MS, Imaging.ImageFormat.Bmp)
End If
PhotoParameter.SqlValue = MS.GetBuffer
SQLCmd.Parameters.Add(PhotoParameter)
Result = SQLCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Dim Msg As String = "Unable to save Client's Picture"
If ex IsNot Nothing Then
Msg &= ":" & ControlChars.NewLine & ControlChars.NewLine & ex.ToString
End If
MessageBox.Show(Msg, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
If Not SQLConn.State = ConnectionState.Closed Then
SQLConn.Close()
End If
End Try
End Using
End If
Return Result
End Function
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles
Dim OpennFileDialog As OpenFileDialog
query = "update tblEmployeeSetup set dbImage = #dbImage where empy_id = '" + txtEmpId.Text + "' "
insertImage(query, "Data Saved...", lblSave, OpennFileDialog )
End Sub
Sub insertImage(ByVal query As String, ByVal message As String, ByVal lblSave As Label, ByVal a As OpenFileDialog)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim result As DialogResult = a.ShowDialog()
' a.FileName = My.Resources.DefultImage.ToString
cmd.Connection = con
cmd.CommandText = query
cmd.Parameters.Add(New SqlClient.SqlParameter("#dbimage", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
lblSave.Text = message
a.Dispose()
Catch ex As Exception
MessageBox.Show("Error" & ex.Message)
Finally
con.Close()
End Try
End Sub

login form using ms access in vb.net

I'm creating a login form for vb.net using ms access 2003 as database. But it only checks for the username and bypasses the password. Meaning that if the username is correct and the password doesn't jive with the username, the user can still enter the system. Here is my code:
Try
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from admintable where AdminName= '" & TextBox4.Text & "' ", cn)
cn.Open()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("AdminName")
NoPas = rdr("AdminPass")
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
adminview.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox4.Clear()
TextBox3.Clear()
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
How do I do it so that it checks both username and password?
You are using a single line IF .. THEN :
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
so the next line will always be executed:
adminview.Show()
you have to rearrange your IF .. THEN conditions
I will share about login system in vb.net using binding navigator that less of coding. just following the link below!
http://www.tesear.com/2011/09/login-system-in-vbnet.html
You could have BOTH the uname and pword in the database and "WHERE" on both, if you get no record back, then you have your answer.
Try using System.String.Compare(String str1,String str2, Boolean ) As Integer like:
If (System.String.Compare(TextBox4.Text, NoAcc, false) And System.String.Compare(TextBox3.Text, NoPas, false)) Then NoAccmod2 = NoAcc
here is the code:
Imports System.Data
Imports System.Data.OleDb
Public Class Form5
Inherits System.Windows.Forms.Form
Dim mypath = Application.StartupPath & "\login.mdb"
Dim mypassword = ""
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Dim sql = "SELECT UserID ,PassID FROM MYTAB WHERE USERID='" & TextBox1.Text & "' AND PASSID='" & TextBox2.Text & "'"
cmd = New OleDbCommand(sql, conn)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MessageBox.Show("Authentication failed...")
Me.Show()
Else
MessageBox.Show("Login successfully...")
Dim frmDialogue As New Form11
frmDialogue.ShowDialog()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Close()
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Me.Hide()
Dim frmDialogue As New Form1
frmDialogue.ShowDialog()
End Sub
Private Sub Form5_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim frm As New Form1
frm.Show()
End Sub
End Class
Try
Dim NoAcc As String
Dim NoPas As String
Dim rdr As OleDbDataReader
Dim cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\mobilestore.accdb;Persist Security Info=False;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from logindata where Username= '" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", cnn)
'NoAcc = TextBox1.Text
'NoPas = TextBox2.Text
cnn.Open()
rdr = cmd.ExecuteReader
If (rdr.Read()) Then
NoAcc = rdr("Username")
NoPas = rdr("password")
If (TextBox1.Text = NoAcc And TextBox2.Text = NoPas) Then
Adminpage.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
End Sub