VB.NET - .accdb database not saving changes - database

I can't figure out why my code won't save to my .accdb database.
I am fetching data from a .accdb database file and displaying it in a DataGridView, and then allowing changes to be made to it there. (This is a stock control system.) After making changes, the user is meant to be able to send the data back so it is saved in the .accdb file.
I have looked online everywhere and tried multiple different ways of doing this. This is the way I am currently using to solve the problem, but when running the code it does not save to the .accdb file. (However, it throws up no errors.)
Public Class Database
Dim datatable As DataTable
Dim adapter As OleDb.OleDbDataAdapter
Dim dbCon As New OleDb.OleDbConnection
Dim dbProvider As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
Dim dbRsrc As String = "Data Source =" & System.IO.Directory.GetCurrentDirectory & "/Resources/List.accdb"
Dim binding As BindingSource
Dim cmdBuilder As OleDb.OleDbCommandBuilder
Private Sub Database_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
adapter = New OleDb.OleDbDataAdapter("Select * FROM List", dbCon)
datatable = New DataTable
adapter.FillSchema(datatable, SchemaType.Source)
adapter.Fill(datatable)
binding = New BindingSource
binding.DataSource = datatable
dbCon.Close()
StockTable.DataSource = binding
End Sub
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
'insert validation here
Try
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
cmdBuilder = New OleDb.OleDbCommandBuilder(adapter)
adapter.AcceptChangesDuringUpdate = True
adapter.Update(datatable)
dbCon.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString() & " Save Unsuccessful.")
End Try
End Sub
End Class
Not sure where I'm going wrong - when I hit the 'save' button, it should connect to the database, build a SQL query to update it and then update my datatable + .accdb database, right?
To test it, I've tried editing multiple columns and saving it, but when opening the file it still says the same values as it had before.
Any suggestions/pointers? I'm pretty newbie to VB.NET, learnt it about 3 months ago and only just starting to get fully into it.

Many thanks to the user "jmcilhinney" who helped me to reach this answer. I feel highly stupid at not realising that my code was working.
I used
Debug.WriteLine("Update value: " & adapter.Update(datatable))
Debug.WriteLine("Connection str: " & dbProvider & dbRsrc)
to find that my update command worked, and that in fact the output of my database file was in the /bin/ folder. I didn't realise that it used the /bin/ folder, and was looking in the root folder with the .VB files, etc.

Related

Database records delete as soon as debugging is stopped

When I enter the fields it works and sends the records to the database and if I clear the form and enter another it also sends that one to the database but when I stop debugging, the database is empty.
Is there something wrong with my code?
What should I do to resolve this issue?
• I am using VB.NET with a Microsoft Access database
• There are two pages of code: Control and Create Account Form
Control
Imports System.Data.OleDb
Public Class DBControl
'CREATE YOUR DB CONNECTION
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=Hotel.mdb;")
'PREPARE DB COMMAND
Private DBCmd As OleDbCommand
'DB DATA
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'QUERY PARAMETERS
Public Params As New List(Of OleDbParameter)
'QUERY STATISTICS
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'RESET QUERY STATS
RecordCount = 0
Exception = ""
Try
'OPEN A CONNECTION
DBCon.Open()
'CREATE DB COMMAND
DBCmd = New OleDbCommand(Query, DBCon)
'LOAD PARAMS INTO DB COMMAND
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
'CLEAR PARAMS LIST
Params.Clear()
'EXECUTE COMMAND & FILL DATABASE
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
'CLOSE YOUR CONNECTION
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
'INCLUDE QUERY & COMMAND PARAMETERS
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Create Account Form
Imports System.Data.OleDb
Public Class Create
Private Access As New DBControl
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=Hotel.mdb")
Private Sub Create_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
AddUser()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
txtForename.Clear()
txtSurname.Clear()
txtNumber.Clear()
txtEmail.Clear()
txtPass.Clear()
txtCity.Clear()
End Sub
Private Sub cbxTitle_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxTitle.SelectedIndexChanged, txtFirst.TextChanged, txtSurname.TextChanged, txtEmail.TextChanged, txtPass.TextChanged
If Not String.IsNullOrWhiteSpace(cbxTitle.Text) AndAlso Not String.IsNullOrWhiteSpace(txtFirst.Text) AndAlso Not String.IsNullOrWhiteSpace(txtSurname.Text) AndAlso Not String.IsNullOrWhiteSpace(txtEmail.Text) AndAlso txtPass.Text.Length = 8 Then
btnCreate.Enabled = True
End If
End Sub
Private Sub AddUser()
'ADD PARAMETERS
Access.AddParam("#Title", cbxTitle.Text)
Access.AddParam("#Forename", txtForename.Text)
Access.AddParam("#Surname", txtSurname.Text)
Access.AddParam("#Number", txtNumber.Text)
Access.AddParam("#Email", txtEmail.Text)
Access.AddParam("#Pass", txtPass.Text)
Access.AddParam("#City", txtCity.Text)
'EXECUTE INSERT COMMAND
Access.ExecQuery("INSERT INTO Customers([Title], [Forename], [Surname], [Number], [Email], [Pass], [City])" &
"VALUES(#Title, #Forename, #Surname, #Number, #Email, #Pass, #City)")
'REPORT & ABORT ON ERRORS
If Not String.IsNullOrEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
DBCon.Close()
End Sub
End Class
Any help is appreciated
Thank you in advance :)
There is a proper way to work with file-based databases in VB.NET.
Add the data file to your project in the Solution Explorer. If you're prompted to copy the file into the project, accept.
Set the Copy To Output Directory property of the data file to Copy If Newer.
Use "|DataDirectory|" to represent the folder path of the data file in your connection string, e.g. Dim connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Hotel.mdb;".
Now you have two copies of your database. You have the one in the project folder, with the other source files, and the one in the output folder, with the EXE. The source file should stay clean, unsullied by test data. The copy in the output folder is the one you connect to when you debug so that's the one you need to look in to find any changes you make while debugging/testing.
Because you set it to only copy when the source file is newer than the output file, any changes you make while testing will not be lost unless you actually make a change to the source file, e.g. add a column or a table. By default, that property is set to Copy Always, which means that your source file is copied over the output file every time the project is built, so any time any source file changes and you run the project again. That's why your data "disappears".

How do I get the selected option from a combobox to display the information from that option in the next page in text boxes?

Sorry, quite difficult to word.
I'm coding a 'surgery database' for a school project and have got so far as to program the login page, which works successfully from the database, and I have coded the directory. The directory combobox displays patients from the database and this functions correctly, but I do not know how to get it so that when you press search, it opens up my main.vb page and fills the textboxes with the correct data from the access database, based upon which patient was selected.
Massive thanks to anyone who can help.
I'm on VB using microsoft access which I haven't really used before. I've tried following tutorials but everything seems slightly different and doesn't get the desired results.
Private Sub BtnPatient_Click(sender As Object, e As EventArgs) Handles BtnPatient.Click
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM PatientDB WHERE [Name] = " & TxtPatient.Text & "'", myConnection)
Dim dr As OleDbDataReader = cmd.ExecuteReader
Me.Visible = False
Me.Hide()
Main.ShowDialog()
myConnection.Close()
End Sub
The output should be the patients details from the access database.

Exception with sqlite database "no such table"

First of all I´m developing a database with autosuggest box. I´ve created a database with DB Browser and imported data. I was reading documentation in C# how connect database and retrieve data. The issue is show up an exception error:
enter image description here
I´ve connected the database in properties with content option. I paste the code:
Public NotInheritable Class METARTAF
Inherits Page
Dim dbpath As String = Path.Combine(ApplicationData.Current.LocalFolder.Path, "airportsdb.sqlite3")
Dim conn As SQLite.Net.SQLiteConnection = New SQLite.Net.SQLiteConnection(New WinRT.SQLitePlatformWinRT(), dbpath)
Dim airportinfo As List(Of String) = Nothing
Public Sub New()
' This call is required by the designer.
InitializeComponent()
End Sub
Private Sub AutoSuggestBox_TextChanged(sender As AutoSuggestBox, args As AutoSuggestBoxTextChangedEventArgs)
Dim datairport As New List(Of String)
Dim retrieve = conn.Table(Of flugzeuginfo)().ToList
If args.Reason = AutoSuggestionBoxTextChangeReason.UserInput Then
If sender.Text.Length > 1 Then
For Each item In retrieve
datairport.Add(item.IATA)
datairport.Add(item.ICAO)
datairport.Add(item.Location)
datairport.Add(item.Airport)
datairport.Add(item.Country)
Next
airportinfo = datairport.Where(Function(x) x.StartsWith(sender.Text)).ToList()
sender.ItemsSource = airportinfo
End If
Else
sender.ItemsSource = "No results..."
End If
End Sub
Private Sub AutoSuggestBox_SuggestionChosen(sender As AutoSuggestBox, args As AutoSuggestBoxSuggestionChosenEventArgs)
Dim selectedItem = args.SelectedItem.ToString()
sender.Text = selectedItem
End Sub
Private Sub AutoSuggestBox_QuerySubmitted(sender As AutoSuggestBox, args As AutoSuggestBoxQuerySubmittedEventArgs)
If args.ChosenSuggestion Is Nothing Then
stationidtxt.Text = args.ChosenSuggestion.ToString
End If
End Sub
Anyone could help about this?
Before you query or insert into a table, you should CREATE it. This tells SQLite what columns you have and suggests datatypes (on other rdbms's you get actual data type enforcement but SQLite does not do that). If this is your problem, you will want to spend some time with the SQLite documentation on data types and the ability to hook them into your application.
On the other hand, as you seem to be trying to retrieve data, this suggess one of two things is wrong. Either you care connecting to the wrong db (in which case SQLite will usually helpfully create an empty db for you!) or else you are specifying the wrong table.

Data transfer using vb.net

I am new to vb.net and very confused at this point. I have experience with vba within excel and have taken a basic vb class at my university but I am clue less when it comes to this.
I have multi projects I would like to try, but I am stuck on how to transfer data, text string from one program to the other using a vb.net app!
I believe the process I am looking for is data binding? is that correct?
The 3 processes I am trying to accomplish.
Excel to Excel text or cell transfer/ copy and paste.
I have file A which is an excel file with rows and columns of data in cells. Then I have file B which is a template with graphs and some other formulas. I am trying to use a vb.net app to open file A copy all the data and paste into a sheet in file B. I have figured out how to open the files but as for the data transfer method I have not found anything.
Private Sub btn_Do_Click(sender As Object, e As EventArgs) Handles btn_Do.Click
Dim txtpath As String
Dim csvpath As String = "C:\Temp"
Dim FileTXT As String
Dim folderpath As String
Dim FinalFile As String
folderpath = "C:\Users\aholiday\Desktop\Data Dump"
FileTXT = cbo_FileList.Text
csvpath = "C:\Temp\" & FileTXT & ".csv"
txtpath = folderpath & "\" & FileTXT & ".txt"
FinalFile = "C:\Users\aholiday\Desktop\Book1"
File.Copy(txtpath, csvpath)
Process.Start("EXCEL.EXE", csvpath)
Process.Start("EXCEL.EXE", FinalFile)
File.Delete(csvpath)
End Sub
Access database to a chart in vb.net app.
Next I have an vb.net app that has a chart in it. How would I get data from an excel file into it. I have no code for this because I am not sure what the method I need is. I need this to be "live" meaning if someone changes something in the excel file it will update on the chart in the app. But the the first step is getting the data out of excel and into the chart. This is the only example I could find and its for Microsoft access as the data source. It didn't work.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)Handles Button1.Click
Chart1.Series.Add("Numbers")
Dim Conn As OleDbConnection = New OleDbConnection
Dim Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
Dim dataFile = "C:\Users\aholiday\Desktop\Database11.accdb"
Conn.ConnectionString = Provider & dataFile
Conn.Open()
'Adds data to chart
Dim cmd As OleDbCommand = New OleDbCommand("Select [Month],[Number] FROM [Table1]", Conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
Chart1.Series("Table1").Points.AddXY(dr("Month").ToString, dr("Number").ToString)
End While
dr.Close()
cmd.Dispose()
End Sub
End Class
Excel to vb.net pictures and text string transfer.
And last. I have an vb.net app that have textbox and picture boxes in the design layout. I have an excel file with strings of text and pictures within cells. I would like code to copy the text and pictures and place them in the textbox and Picturebox.
I would like to learn how one would accomplish any of those.Please post any helpful content from sources. Any suggestions and especially examples would be awesome. Please nothing from Microsoft unless it crystal clear. I have spent about a day researching and googled everything I could think of and have found very little. None that work when I try to use it.
Thank you

VB.NET issue loading textboxes with data from SQL Server

I have some textboxes (using VS2010) I'm trying to populate with values from columns in a SQL Server database based on what item someone selects from a combobox. At first I was able to display the values for the first item in the combobox, but now nothing at all displays when I debug. Code:
Private Sub loadfields(sender As System.Object, e As System.EventArgs) Handles client_selection_combobox.SelectedIndexChanged
Using myconnection As New SqlConnection("connection string")
Dim loadfields As String = "SELECT company FROM ClientFileDatabase WHERE ClientFileDatabase.File_Name=#company;"
Dim loadfields_sqlcommand As New SqlCommand(loadfields, myconnection)
loadfields_sqlcommand.Parameters.Add("#company", SqlDbType.NVarChar)
loadfields_sqlcommand.Parameters("#company").Value = client_selection_combobox.SelectedIndex.ToString
Dim loadfields_dataadapter As New SqlDataAdapter
loadfields_dataadapter.SelectCommand = loadfields_sqlcommand
Dim loadfields_dataset As DataSet = New DataSet()
loadfields_dataadapter.Fill(loadfields_dataset, "ClientFileDatabase")
Dim loadfields_dataview = New DataView(loadfields_dataset.Tables("ClientFileDatabase"))
companyname_textbox.DataBindings.Clear()
companyname_textbox.DataBindings.Add("Text", loadfields_dataview, "Company")
taxid_textbox.DataBindings.Clear()
taxid_textbox.DataBindings.Add("Text", loadfields_dataview, "TaxIDNumber")
accountmanager_textbox.DataBindings.Clear()
accountmanager_textbox.DataBindings.Add("Text", loadfields_dataview, "AccountManager")
etc...
End Using
End Sub
I've also tried using the SelectedValueChanged and SelectionChangeCommitted event handlers to no avail. Also tried using a refresh after setting the databindings, didn't help. Any advice welcome, thanks!
I personally like to use datatables, I find them easier to work with. I'm sure you will have more code to check to make sure dt.rows.count > 0 before actually attempting to work with the data, but here is how I would do it.
Dim loadfields_dataadapter As New SqlDataAdapter
Dim dt As New DataTable
loadfields_dataadapter.Fill(dt)
companyname_textbox.text = dt.Rows(0).Item("Company")
taxid_textbox.text = dt.Rows(0).Item("TaxIDNumber")
accountmanager_textbox.text = dt.Rows(0).Item("AccountManager")
Also, keep in mind that NULL fields in the database can cause runtime errors, so you may have to check for those as well.

Resources