Cannot connect to Access using VB.net - vb.net

i want to create a login page for my application. and when everything has finished and i want to login it always shows
Error :
The Microsoft Jet database engine cannot open the file 'C:\Users\Gio\Documents\Visual Studio 2012\Projects\CSS\CSS\bin\Debug'. It is already opened exclusively by another user, or you need permission to view its data.
Code :
Imports System.Data.OleDb
Public Class Login
Dim path = System.Windows.Forms.Application.StartupPath
Private Sub Login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub loginbtn_Click(sender As Object, e As EventArgs) Handles loginbtn.Click
Dim connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Gio\Documents\Visual Studio 2012\Projects\CSS\CSS\bin\Debug;")
Dim command As New OleDbCommand("SELECT [ID] FROM [User] WHERE [usernameField] = Username AND [passwordField] = Password", connection)
Dim usernameparam As New OleDbParameter("Username", Me.usernamebox.Text)
Dim passwordparam As New OleDbParameter("Password", Me.passwordbox.Text)
command.Parameters.Add(usernameparam)
command.Parameters.Add(passwordparam)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("Login Succesful!")
passwordbox.Text = ""
Me.Hide()
Main.Show()
Else
MessageBox.Show("Username and Password are incorrect!")
passwordbox.Text = ""
End If
command.Connection.Close()
End Sub
Private Sub exitbtn_Click(sender As Object, e As EventArgs) Handles exitbtn.Click
Me.Close()
End Sub
End Class

Change this line
Dim connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Gio\Documents\Visual Studio 2012\Projects\CSS\CSS\bin\Debug;")
to
Dim connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Gio\Documents\Visual Studio 2012\Projects\CSS\CSS\bin\Debug\YourMSAccessDB.mdb;")
or to load the db in your output directory
Dim connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\YourMSAccessDB.mdb;")
'".\" is equivalent to your output directory or where your application (exe file) is located.

Related

No value given for one or more required parameters while trying to access a picture file from an Acces database using VB.net

Im doing a school project. and I was testing a login form for my app. I'm trying separately from my login form and a profile pic form. I have successfully managed to save the image to the access database but I have had quite a few problems trying to display it on a textbox on my form.
This is the whole app code:
Imports System.Data.OleDb
Imports System.IO
Public Class Form2
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb")
Dim cmd As New OleDbCommand
Dim sql As String
Dim da As New OleDb.OleDbDataAdapter
Dim result As Integer
Private Sub saveimage(sql As String)
Try
Dim arrimage() As Byte
Dim mstream As New System.IO.MemoryStream
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
arrimage = mstream.GetBuffer()
Dim Filesize As UInt32
Filesize = mstream.Length
mstream.Close()
con.Open()
cmd = New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#Imagen", arrimage)
.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
.ExecuteNonQuery()
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
'End Try
Public conex As New OleDbConnection()
Public Sub conexion()
conex.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
conex.Open()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles BTNGuardar.Click
sql = "Insert into TBImg (Imagen, Nombre) Values (#Imagen, #Nombre)"
'sql = "Insert into TBImg (Imagen) Values (#Imagen)"
saveimage(sql)
MsgBox("Image has been saved in the database")
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
OpenFileDialog1.Filter = "Imagenes JPG|*.jpg|Imagenes PNG|*.png"
OpenFileDialog1.RestoreDirectory = True
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Try
With OpenFileDialog1
'CHECK THE SELECTED FILE IF IT EXIST OTHERWISE THE DIALOG BOX WILL DISPLAY A WARNING.
.CheckFileExists = True
'CHECK THE SELECTED PATH IF IT EXIST OTHERWISE THE DIALOG BOX WILL DISPLAY A WARNING.
.CheckPathExists = True
'GET AND SET THE DEFAULT EXTENSION
.DefaultExt = "jpg"
'RETURN THE FILE LINKED TO THE LNK FILE
.DereferenceLinks = True
'SET THE FILE NAME TO EMPTY
.FileName = ""
'FILTERING THE FILES
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png|(*.jpg)|*.jpg|All files|*.*"
'SET THIS FOR ONE FILE SELECTION ONLY.
.Multiselect = False
'SET THIS TO PUT THE CURRENT FOLDER BACK TO WHERE IT HAS STARTED.
.RestoreDirectory = True
'SET THE TITLE OF THE DIALOG BOX.
.Title = "Select a file to open"
'ACCEPT ONLY THE VALID WIN32 FILE NAMES.
.ValidateNames = True
If .ShowDialog = DialogResult.OK Then
Try
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
Catch fileException As Exception
Throw fileException
End Try
End If
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conexion()
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub BtnBuscar_Click(sender As Object, e As EventArgs) Handles BtnBuscar.Click
Dim arrimage() As Byte
Dim conn As New OleDb.OleDbConnection
Dim Myconnection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
conn.ConnectionString = Myconnection
conn.Open()
sql = "Select * from TBImg where Nombre=" & (TBBuscar.Text)
Dim cmd As New OleDbCommand
With cmd
.Connection = conex
.CommandText = sql
End With
Dim publictable As New DataTable
Try
da.SelectCommand = cmd
da.Fill(publictable)
TextBox1.Text = publictable.Rows(1).Item("Nombre").ToString
arrimage = publictable.Rows(1).Item("Imagen")
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
Catch ex As Exception
MsgBox(ex.Message)
Finally
da.Dispose()
conn.Close()
End Try
End Sub
End Class
the relevant part is at Private Sub BtnBuscar_Click.
I'm trying to search in a textbox for the name that I saved the image with. but I haven't had success all I get is the error of the title.
this is how my database looks like the images are saved as an ole object
This is the error I get
I was following this tutorial https://www.youtube.com/watch?v=zFdjp39mfhQ
but he didn't quite explain how to use the:
TextBox1.Text = publictable.Rows(0).Item(1)
arrimage = publictable.Rows(0).Item(1)'
don't know if it's the cause of the issue.
instructions. The reason why my code looks different is that I was trying to stuff to see if I could make it work.
I have tried to search for answers and people suggest that I may have put the table name wrong or the column but I copied the name exactly how it is in the table with ctrl + c and ctrl + v.
what I want is that when I type the name in the column name of the database that it brings the designated picture stored as ole object onto my desired picture box on my form app.
Needless to say, I'm not that experienced with vb.net and SQL, Acces. I'm just following tutorials for being able to complete the project.
Do not declare connections or commands or datareaders at the class level. They all need to have their Dispose methods called. Using blocks will have the declare, closing and disposing even if there is an error. Streams also need Using blocks.
Defaults for an OpenFiledialog
Multiselect is False
CheckFileExists is True
CheckPathExists is True
DereferenceLinks is True
ValidateNames is True
FileName is ""
Unless you are getting paid by the line, it is unnecessary to reset these values to their defaults.
I have alerted your Filter to exclude All Files. You also had jpg appearing twice.
I declared a variable to hold the file extension, PictureFormat, of the image file so you could provide the proper parameter for ImageFormat.
When you retrieve the image field from the database it comes as an Object. To get the Byte() a DirectCast should work.
Private PictureFormat As String
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
FillPictureBoxFromFile()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles BTNGuardar.Click
Try
saveimage()
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
MsgBox("Image has been saved in the database")
End Sub
Private cnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
Private Sub saveimage()
Dim arrimage() As Byte
Using mstream As New System.IO.MemoryStream
If PictureFormat.ToLower = ".png" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
ElseIf PictureFormat.ToLower = ".jpg" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
arrimage = mstream.GetBuffer()
Dim Filesize As Long
Filesize = mstream.Length
End Using
Using con As New OleDbConnection(cnStr),
cmd As New OleDbCommand("Insert into TBImg (Imagen, Nombre) Values (#Imagen, #Nombre)", con)
With cmd
.Parameters.Add("#Imagen", OleDbType.Binary).Value = arrimage
.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
con.Open()
.ExecuteNonQuery()
End With
End Using
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
FillPictureBoxFromFile()
End Sub
Private Sub BtnBuscar_Click(sender As Object, e As EventArgs) Handles BtnBuscar.Click
Dim dt As DataTable
Try
dt = GetDataByName(TBBuscar.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
TextBox1.Text = dt(0)("Nombre").ToString
Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
End Sub
Private Function GetDataByName(name As String) As DataTable
Dim dt As New DataTable
Using conn As New OleDb.OleDbConnection(cnStr),
cmd As New OleDbCommand("Select * from TBImg where Nombre= #Buscar", conn)
cmd.Parameters.Add("#Buscar", OleDbType.VarChar).Value = TBBuscar.Text
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub FillPictureBoxFromFile()
With OpenFileDialog1
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png"
.RestoreDirectory = True
.Title = "Select a file to open"
If .ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
PictureFormat = Path.GetExtension(OpenFileDialog1.FileName)
End With
End Sub

How can I make a datagridview live connected to an access database stored locally in VB.NET?

I would like it so when I delete/edit a record from the datagridview, it will automatically delete/edit the access database file. Here is a snippet of my code which loads the database into the datagridview.
Public Function dbConnect() As Boolean
Try
cn = New OleDbConnection(DataBasePath)
cn.Open()
'MessageBox.Show("is work ")
Return True
Catch ex As Exception
MessageBox.Show("Unable to open the database: " & ex.Message)
Return False
End Try
End Function
Private Function GetOrders() As DataTable
Dim dtOrders As New DataTable
dbConnect()
Dim SQLCMD As New OleDbCommand
SQLCMD.Connection = cn
SQLCMD.CommandText = "Select * From [OrdersTbl]"
dtOrders.Load(SQLCMD.ExecuteReader())
Return dtOrders
End Function
Private Sub EditOrdersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OrdersDataGrid.DataSource = GetOrders()
End Sub
How can I make it so that changes are saved to the local file.
I have a datagridview and a button on the form. Here's the code you can refer to:
Private dt As DataTable = New DataTable
Private da As OleDbDataAdapter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As OleDbConnection = New OleDbConnection("your connection string")
connection.Open()
Dim cmdTxt As String = "SELECT * FROM yourTable"
da = New OleDbDataAdapter(New OleDbCommand(cmdTxt, connection))
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(dt)
Dim source As BindingSource = New BindingSource With {
.DataSource = dt
}
DataGridView1.DataSource = source
connection.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DataGridView1.EndEdit()
da.Update(dt)
End Sub
Every time you want to update database from your datagridview, just click the button.

Update statement in sql doesnt work , microsoft access with vb.net

I currently doing the changepassword function in my vb.net project, user can click change password to change their password
But my code doesnt update correctly , it will show "updated" but when i go to my database access table the data still remain the same
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.IO
Public Class frmUserDetail
Dim ds As New DataSet
Dim dt As New DataTable
Dim cmd As SqlCommand
Dim con As SqlConnection
Dim da As New OleDbDataAdapter
Dim conn As New OleDbConnection
Private Sub FrmUserDetail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
loadUserDetail()
txtUserName.Enabled = False ' set it to false so user cannot do shit with it
End Sub
Public Sub loadUserDetail()
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
Dim cmd As OleDbCommand
Dim userName As String = frmMain.lblUserLogin.Text
'specify name of the user
Dim search As String = "SELECT * from tblUser WHERE UserName= '" + userName + "'"
cmd = New OleDbCommand(search)
cmd.Connection = conn
Dim dtt As New DataTable()
Dim daa As New OleDbDataAdapter(cmd)
daa.Fill(dtt)
If dtt.Rows.Count() > 0 Then
txtUserName.Text = dtt.Rows(0)(0).ToString 'show the userName
txtUserPassword.Text = dtt.Rows(0)(1).ToString 'show the password of the user
txtEmail.Text = (dtt.Rows(0)(2).ToString) 'show user email
Else
MsgBox("You are currently login as a guest")
End If
End Sub
Private Sub changePassword()
If cbChangePassword.Checked Then
txtChangePassword.Enabled = True
Else
txtChangePassword.Enabled = Not (True)
End If
End Sub
Private Sub CbChangePassword_CheckedChanged(sender As Object, e As EventArgs) Handles cbChangePassword.CheckedChanged
changePassword()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
conn.Open()
Dim cmd As OleDbCommand
Dim sql As String = "UPDATE tblUser SET UserPassword=#userpass,Email=#email WHERE UserName=#userName;"
cmd = New OleDbCommand(sql.ToString, conn)
cmd.Parameters.AddWithValue("#username", txtUserName.Text)
cmd.Parameters.AddWithValue("#userpass", txtChangePassword.Text)
cmd.Parameters.AddWithValue("#email", txtEmail.Text) 'pass the time variable from the form 1 to the parameter
cmd.ExecuteNonQuery()
MsgBox("updated")
conn.Close()
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Hide()
frmMain.Show()
End Sub
End Class
I Expect my database will get updated when i updated it

My Oledb DataAdapter.Fill code is "missing parameters"

I am trying to set-up a login page that checks the user's credentials from an MS Access database. When I run the code, it says that the fill method needs one or more parameters. Here's the code I'm using:
Public Class login
Public Shared dslogin As New DataSet
Public Shared con As New OleDb.OleDbConnection
Dim da1 As New OleDb.OleDbDataAdapter
'Global variables
Public Shared currentloginID As Integer = 0
Public Shared tbusername As TextBox
Public Shared tbpassword As TextBox
Private Function OpenDBConnection1()
Dim directory1 As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Return "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = " & directory1 & "\IEshiDBv1.accdb"
End Function
'login button
Private Sub btnLOGIN_Click(sender As Object, e As EventArgs) Handles btnLOGIN.Click
Dim username As String = txtusername.Text
Dim password As String = txtpassword.Text
If username = "" Or password = "" Then
MsgBox("Please enter log-in details")
con.Close()
Exit Sub
Else
Dim sqllogin As String = ("SELECT * FROM LoginRcrds WHERE LoginUserName = " & username)
da1 = New OleDb.OleDbDataAdapter(sqllogin, con)
da1.Fill(dslogin, "LoginCredentials")
con.Close()
Dim dtlogin As DataTable = dslogin.Tables("LoginCredentials")
Dim rowlogin As DataRow
For Each rowlogin In dtlogin.Rows
If password = rowlogin("LoginPW") Then
homepage.Show()
Me.Hide()
Exit For
End If
Next
MsgBox("Incorrect log-in credentials. Please try again")
Exit Sub
End If
End Sub
'Onload subroutine
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = (OpenDBConnection1())
con.Open()
End Sub
End Class
The error occurs at
da1.Fill(dslogin, "LoginCredentials")
and the error message says " No value given for one or more required parameters."
I read somewhere that .Fill requires three parameters: (DataSet, RecordSet, TableName). I never tried this because I don't understand what RecordSet means.
Edit: I've checked another program with a 4.0 Oledb provider and changed it to 12.0. The same error appeared. It seems that the Fill method of the DataAdapter of Oledb 12.0 requires more than 2 parameters. Can somebody explain this?

Problems passing values from one form to another

I'm new to VB.net. So here is what I want to do which I am having some serious problem
Using the "Get_Computer_Name form" will post the username and account type into another form. The Get_Computer_Name also gets the computer name where it will be sent to a module and that module will work as the main connection. Now I have tried to separate the login form and form that gets the computer name but that didn't work (I also want to try that method).
The problem with my current method is that it can only perform one thing at a time. It fails to post the username and account type and it fails to send the computer name to the module. Now strangely there is a way around. If I comment out the post username and account type, the computer name will be sent to the module and the module will work and connect to the database. Now if I choose not to comment out the code that post the username and account to the other form, the computer name won't be sent to the module that handles the connection thus failing to connect to the database.
I am open to other suggestions rather than doing it this way.
Thank you
'Here is my code for "Get_Computer_Name form"
Imports System.Data.SqlClient
Public Class Get_Computer_Name
Public Sub Get_Computer_Name_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cmbcomputername.Text = My.Computer.Name
connect()
End Sub
Private Sub cmbcomputername_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbcomputername.SelectedIndexChanged, cmbcomputername.TextChanged
cmbcomputername.Text = My.Computer.Name
End Sub
Public Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
datasource = cmbcomputername.Text
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim reader As SqlDataReader
Dim sqlstatement As SqlCommand = New SqlCommand
sqlstatement.Connection = connection
Try
sqlstatement.CommandText = "Select account_username, account_password, account_type " &
"from account_login where account_username='" & txtusername.Text & "' and account_password='" & txtpassword.Text & "'"
reader = sqlstatement.ExecuteReader()
If (reader.Read()) Then
Dim application_form As application_form
application_form = New application_form
application_form.Show()
application_form = Nothing
Me.Visible = False
'This is the code that post the username and account type to the other form (application form). If I comment this code out, the system successfully connects to the database
application_form.lblusername.Text = (reader("account_username").ToString)
application_form.lblaccount_type.Text = (reader("account_type").ToString)
sqlstatement.Dispose()
reader.Close()
connection.Close()
Else
connection.Close()
MsgBox("Invalid")
End If
reader.Close()
Catch ex As Exception
End Try
End Sub
End Class
'This is the code for the module that holds the main connection string
Public connection As SqlConnection = New SqlConnection
Public datasource As String
Public database As String = "bpmi"
Public sqlmainconnector As String
Public Sub connect()
sqlmainconnector = "Data Source=" & datasource & ";Initial Catalog=bpmi;Integrated Security=True"
connection.ConnectionString = sqlmainconnector
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
Else
connection.Close()
End If
Catch ex As Exception
End Try
End Sub
'And this code is the form where the username and account type will be posted
Imports System.Data.SqlClient
Public Class application_form
Dim sqlcommand As SqlCommand
Dim da As SqlDataAdapter
Dim table As New DataTable
Dim dategrabberapp As String
Dim dategrabberben As String
Dim benidgrabber As String
Private Sub Form1_Load(sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connect()
filldatagrid(updateappdatagrid, updatebendatagrid)
fillcomboboxstatus(cmbstatus)
fillcomboboxposition(cmbappworkposition)
fillcomboboxrelationship(cmbrelation)
fillcomboboxrelationshipupdate(cmbrelationbenupdate)
fillcomboboxstatusupdate(cmbappstatusupdate)
fillcomboboxpositionupdate(cmbappworkposupdate)
'this is where the account type will got to
If lblaccount_type.Text <> "Administrator" Then
Me.TabControl1.TabPages(1).Enabled = False
Me.TabControl1.TabPages(2).Enabled = False
MsgBox("As a 'Staff', you are not permitted to do any updates")
updateappdatagrid.Hide()
updatebendatagrid.Hide()
End If
End Sub
End Class