Could not find file "...\bin\Debugdb.mdb" when trying to open an Access .mdb file - vb.net

I'm trying to make a very simple application that connects to an Access 2003 database.
I built a very simple user interface with 7 labels and 7 text-box with only 2 buttons: one of them is "Save" and the other one is "Exit".
Inside my form I added the code :
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
'Try
Dim saveinto As New OleDb.OleDbCommand
Dim constr As String = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "db.mdb"
Dim conn As New OleDb.OleDbConnection(constr)
saveinto.Connection = conn
saveinto.CommandType = CommandType.Text
saveinto.CommandText = " insert into users(id,username,nid,money,mode,help,yesorno) " & " values ('" & TextBox7.Text & "' ,'" & TextBox1.Text & "' , '" & TextBox2.Text & "','" & TextBox3.Text & "' , '" & TextBox4.Text & "' , '" & TextBox5.Text & "' , '" & TextBox6.Text & "')"
conn.Open()
saveinto.ExecuteNonQuery()
conn.Close()
MsgBox("All Done :P ")
Exit Sub
End Sub
when i press the Save Button i got that error :
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll`
and its the first time to see it, i thought that something wrong in my system (WinVista:) or database (build with my Access 2007 then converted to 2003) and i uninstall Access 2007 and install 2003 then rebuild new database and replace the old one with it.
When i run my app and press the Save Button i got the same error Message with
OledbException was unhandled Could not find file 'C:\Users\Mahmoud\Documents\Visual Studio 2008\Projects\Test\Test\bin\Debugdb.mdb.
i searched here before asking my question for my problem but i couldn't find the same problem and and i tried to apply some suggestions from similar errors but nothing happened so forgive me if duplicated a question and please HELP.
thanks

It appears that Application.StartupPath returns
C:\Users\Mahmoud\Documents\Visual Studio 2008\Projects\Test\Test\bin\Debug
and that does not have a trailing backslash (\), so when you append db.mdb to it you get a path that does not actually point to your database file. Try
... Application.StartupPath & "\db.mdb"
instead.

Related

object reference not set to an instance of the object Error when adding data into my database

I am having a problem when i am trying to put this data into my database
I'm using Vstudio 2013 and MS Access as my database
my problem is everytime i click add to add the data in my database this error always popping object reference not set to an instance of the object. even i declared the
Here's my Add button Code
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
cmd.Connection = cn
cmd.CommandText = "INSERT INTO gradess ( StudentNo,StudentName,StudentSection,SubjectNo1,SubjectNo2,SubjectNo3,SubjectNo4,SubjectNo5,SubjectNo6,SubjectNo7,SubjectNo8,TotalAverage) " & "Values('" & txtStudentNo.Text & "','" & lblName.Text & "','" & lblSection.Text & "','" & txtSubject1.Text & "','" & txtSubject2.Text & "','" & txtSubject3.Text & "','" & txtSubject4.Text & "','" & txtSubject5.Text & "','" & txtSubject6.Text & "','" & txtSubject7.Text & "','" & txtSubject8.Text & "','" & lblTotalAverage.Text & "')"
cmd.ExecuteNonQuery()
refreshlist()
disablebutton()
MsgBox("Successfully Added!!", vbInformation, "Successful")
clear()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
When you declare a variable like Dim cn As OleDb.OleDbConnection you are just telling the compiler what type it is not creating an object of that type.
When you use the New keyword OleDb.OleDbConnection is not just the name of a class (the data type) but it is an actual method. It is calling the constructor of the class which returns an instance of the object.
In C# you are required to put the parenthesis after like OleDb.OleDbConnection() which shows you are calling a method. You can add the parenthesis in vb.net but it is not required but I think it is a good reminder of the difference between setting a data type and creating an object.
Your declaration should be : Dim cn As New OleDb.OleDbConnection Dim cmd As New OleDb.OleDbCommand
– F0r3v3r-A-N00b 20 mins ago

Error: Provider not registered on local machine

I am connecting an access database to a datagrid view on vb and I am encountering an error
"Additional information: The 'Microsoft.ACE.OLEDB.12.0Data Source =
CUBSDatabase.accdb' provider is not registered on the local machine."
I am using visual studio version 2015, language visual basic.
My access database is saved in the bin in the debug folder
This is my code so far;
Any idea how to get rid of the error?
The error renders on the line // adt.Fill(datatable)
Imports System.Data.OleDb
Public Class Form1
Dim dbconn As New OleDbConnection
Dim adt As New OleDbDataAdapter
Dim ds As New DataSet
Dim datatable As New DataTable
Dim cmd As New OleDbCommand
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbconn.ConenctionString = ("Provider=Microsoft.ACE.OLEDB.12.0" &
"Data Source = CUBSDatabase.accdb")
showData()
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
adt = New OleDbDataAdapter("insert into Student (FName, SName, Attendance, CA1, CA2, FinalExam) values ( '" & txtFName.Text & "','" & txtSName.Text & "', '" & txtAttendance.Text & "', '" & txtCA1.Text & "', '" & txtCA2.Text & "', '" & txtFinalExam.Text & "', )", dbconn)
adt.Fill(ds)
ds = New DataSet
MsgBox("Saved")
End Sub
Private Sub showData()
Dim dbcommand As String
dbcommand = "SELECT * FROM Students"
adt = New OleDbDataAdapter(dbcommand, dbconn)
datatable = New DataTable
adt.Fill(datatable)
DataGridView1.DataSource = datatable
End Sub
End Class
Maybe you just forgot a semicolon in your code, after your provider name, since normally you should have something like
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=...
If that's not your case, as per this answer to a similar question, you need to install the provider on your machine; as a preliminary check, you can follow another answer to the same question and see wheter you already have the dll including your provider, i.e. ACEOLEDB.DLL, at one of these paths:
C:\Program Files\Common Files\Microsoft Shared\OFFICE14
C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE14
Of course you can adapt those paths to the Office version you have on your machine, which are listed in this answer, e.g.
Office 2007 12
Office 2010 14
Office 2013 15
Office 2016 16
EDIT: the following won't apply because Jet won't handle accdb files.
Last but not least, if you don't feel like installing anything or you want to perform a quick check of your code functionality, you can rewrite your connection string to use an older (legacy, perhaps despised) provider, i.e. Jet, which is included in Windows:
dbconn.ConenctionString = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = CUBSDatabase.accdb")
Of course there's a difference in terms of efficiency between the two.
Use this format.
Dim cons As String = "provider= Microsoft.ACE.OLEDB.12.0; Data Source=D:\Users\rjimenez\Documents\QAdatabase.mdb"
but of you still got an error. Download
AccessDatabaseEngine
Hope it will works!

Update Access database using Visual Studio 2015 - VB.net

I am trying to do a simple update to an Access 2016 database. I am using Visual Studio/VB.net. I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore). I have tried two different ways to do this...using the update table adapter, for example:
MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
AvailabilityTextBox.Text, EmailTextBox.Text)
Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
But this method gives me the error of Syntax Error in UPDATE statement. Again I have used this method elsewhere with no problems. Below I will post all the code for this form.
Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class editMediators
Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")
' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
Dim cmd As New OleDbCommand
connect() ' open our connection
Try
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
MsgBox("Data Has Been Saved !", vbInformation)
Catch ex As Exception
MsgBox("Error when saving data: " & ex.Message)
End Try
End Sub
Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
DateTimePicker1.Value = Today()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
NewData = True
alertMsgBox2()
End Sub
Private Sub alertMsgBox2()
Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
"No: Exits the mediator update window without saving," & vbNewLine &
"Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
Case MsgBoxResult.Yes
MediatorsListBindingSource.EndEdit()
updateMediator()
'intentionally commented out
'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
'AvailabilityTextBox.Text, EmailTextBox.Text)
' Me.Close()
Case MsgBoxResult.No
MediatorsListBindingSource.CancelEdit()
Me.Close()
End Select
End Sub
Private Sub updateMediator()
Dim saveInfo As String
If NewData Then
Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
If Message = vbNo Then
Exit Sub
End If
Try
'Update mediator information
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
Catch ex As Exception
End Try
Else
Exit Sub
End If
runAccessSQL(saveInfo)
End Sub
There is obviously something I am missing, though I am not sure it is missing from the code. I checked my database fields and set them to string/text fields just to see if I could get it working. At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements. I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since. I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.
I am rather lost on what else to try as this seems like it should work one way or another. Any ideas what to look at and/or try?? Hopefully I can be pointed in the right direction.
Thanks :)
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.
Try this instead:
(Edited)
saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
mediatorID = '" & MediatorIDTextBox.Text & "'"
Also be sure to handle the date correctly. I usually force formatting in yyyy/mmm/dd format.

Having trouble inserting data to mysql datetimepicker [duplicate]

This question already has answers here:
How to compare two dates FORMATS for saving to DB
(3 answers)
Closed 6 years ago.
How do you insert data into the database using datetimepicker in VB.NET? I tried to convert it using:
Format(name_of_the_datetimepicker.Value, "yyyy-MM-dd") in my SQL statement but I don't know where did I go wrong.
Here is my code:
Imports MySql.Data.MySqlClient
Public Class frmMain
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Not conn Is Nothing Then
conn.Close()
End If
conn = New MySqlConnection("Data Source=" & Server & ";user id=" & UserName & ";password=" & PassWord & ";database=" & DatabaseName & ";")
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
Dim cmdSave As MySqlCommand
Dim sql As String
sql = "INSERT INTO (rental_date, inventory_id, customer_id, return_date, staff_id) VALUES ('" & Format(dt_picker_rental_date.Value, "yyyy-MM-dd") & "', '" & txt_inventory_id.Text & "', '" & txt_customer_id.Text & "', '" & Format(dt_picker_return_date.Value, "yyyy-MM-dd") & "', '" & txt_staff_id.Text & "')"
Try
cmdSave = New MySqlCommand(sql, conn)
cmdSave.ExecuteNonQuery()
MsgBox("Success!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
DO NOT use string concatenation to insert data into SQL code. ALWAYS use parameters. Parameters maintains all data in binary form so format is never an issue. More importantly, you are protected from SQL injection. Using a date, that could look like this:
Dim command As New MySqlCommand("INSERT INTO MyTable (DateColumn) VALUES (#DateColumn)", connection)
command.Parameters.AddWithValue("#DateColumn", myDateTimePicker.Value)
If you want to insert just the date without the time then use Value.Date instead of just Value.
More info on ADO.NET parameters here:
http://jmcilhinney.blogspot.com.au/2009/08/using-parameters-in-adonet.html
Try this. It may help you.
cmd.Parameters.Add("date", OleDbType.DBDate).Value = DateTimePicker1.Value

Can someone assist me in getting data to display in a DataGridView vb.net?

I didnt have much luck when I posted about this when I was programming this application a different way, so I redid the program using DataAdapter instead of the TableAdapter method.
I need help getting data to display inside the DataGridView tool in vb.net Im not sure what i'm doing wrong here... The data displays in the listbox just fine. but will not display in the DataGridView tool. The DataGridView will display the length of the string. Unsure why... See my code below. (BTW, I created the listbox just for testing purposes and dont want to use that)
What the program does: A user places a checkmark on each house project (ex: cement work) and the project gets the list of tools required for the selected project(s). The project names are in checkboxes and checkChanged event assings the text to the variable "ProjectName" in the SQL select statement.
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim connection As OleDbConnection
Dim cmdString As String = "Select Distinct ToolName,Notes From Tools Where ProjectName = '" & carpentry & "' or ProjectName = '" & cementWork & "' Or ProjectName= '" & dryWall & "' Or ProjectName = '" & electrical _
& "' Or ProjectName = '" & HVAC & "' Or ProjectName = '" & laminateFlooring & "' Or ProjectName = '" & painting & "' Or ProjectName = '" & plumbing _
& "' Or ProjectName = '" & texture & "' Or ProjectName = '" & tileWork & "' Or ProjectName = '" & vinylFlooring & "'"
connection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=SaintEnterprises.mdb")
Dim adapter As New OleDbDataAdapter(cmdString, connection)
Dim tools As New DataSet
connection.Open()
adapter.Fill(tools)
Dim toolslist As New List(Of String)
ListBox1.Items.Clear()
For Each row As DataRow In tools.Tables(0).Rows
Dim s As String = row("toolname").ToString
'toolslist.Add(row("toolName").ToString) 'Does same thing as line toollist.add(s) below
toolslist.Add(s.ToString) 'add to List
ListBox1.Items.Add(s.ToString) 'Displays the type of tools based on the query.
Next
ToolsDataGridView.DataSource = toolslist 'displays the length (Total # of letters) of each toolname'
End Sub
Although I probably wont go back to doing it using Table adapter, if you'd like To see my way of programming this application using TableAdapter, see this link.
I think you need a DataTable to fill your DataGridView. Convert you DataSet-Rows to a DataTable.
I've tried this and this works fine for me (assuming, your database connection is working).
Dim oData As New System.Data.DataTable
For Each oRow As System.Data.DataRow In tools.Tables(0).Rows
oData.ImportRow(oRow)
Next
ToolsDataGridView.DataSource = oData