Database records delete as soon as debugging is stopped - database

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

Related

How do I display access database in VB?

So I have been able to connect my database to VB forms, and I am also able to see the table and the fields within. But I can't figure how to make the data appear in the table because it's just blank.
I do have some data stores in the actual access database but it won't show up in my program.
Is there a particular code I need to write? This is what I have so far. The database is called the 'POS system'.
Private Sub OrdersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles OrdersBindingNavigatorSaveItem.Click
Me.Validate()
Me.OrdersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.POS_systemDataSet)
End Sub
It is usually a good idea to separate your database code from your user interface code. Create a connection and a command in a Using block so they will be closed and disposed at End Using. Pass the connection string to the constructor of the connection. Pass the CommandText and connection to the constructor of the command. Open the connection and execute the command returning a DataReader to load the DataTable.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetData()
DataGridView1.DataSource = dt
End Sub
Private Function GetData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("Select * From SomeTable;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function

How to get SQL Query Stats/ Progress message dynamically using T-SQL command?

In my application I want the show the SQL Query progress. For example, assume a user clicked on a backup button, then I want him to be able to view the progress of the query he made in case the database is too big to restore or backup. At first I tried to do this by assuming how much disk space the database might take before even start backing up and then using that with the copying rate to estimate a time it might take to backup. But unfortunately I failed. Then by luck I found one lovely T-SQL command that show the stats when used in SSMS and it is just using an extra line 'With Stats = [Some integer] e.g. 1, 10, 20, etc' but here is the problem. I cannot find any work through for this to work with Vb.Net aka my application.
I found this awesome query from this link (www.mssqltips.com). If you open the website you can see few examples showing this.
The code to get stats:
Use dbName Backup dbName To Disk='BackupLocation' With STATS = 10
Edit #1:
Adding these lined of code now does showing the InfoMessage I was searching for but still not useful as this shows up only when the full operation is completed.
But what I want is to show them dynamically.
Code that worked:
AddHandler con.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
Private Sub OnInfoMessage(ByVal sender As Object, ByVal e As System.Data.SqlClient.SqlInfoMessageEventArgs)
strInfo.AppendLine(e.Message)
txtMsg.Text = strInfo.ToString
End Sub
My complete code:
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Text
Public Class BackupForm
Dim ConnectionString As String = My.Settings.LADBConnectionString
Dim con As SqlConnection = New SqlConnection(ConnectionString)
Dim cmd As New SqlCommand()
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Using OFD As New SaveFileDialog
With OFD
.FileName = "Backup " + Now.ToString("dd-MM-yyyy")
.Filter = "Log Application Backup |*.bak"
.CheckFileExists = False
.OverwritePrompt = False
Select Case .ShowDialog
Case DialogResult.OK
If .FileName <> "" Then
txtBackup.Text = .FileName
End If
End Select
End With
End Using
End Sub
Private Sub btnBackup_Click(sender As Object, e As EventArgs) Handles btnBackup.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Dim strInfo As New StringBuilder
Private Sub OnInfoMessage(ByVal sender As Object, ByVal e As System.Data.SqlClient.SqlInfoMessageEventArgs)
strInfo.AppendLine(e.Message)
txtMsg.Text = strInfo.ToString
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim backupQuery As String = $"use LDDB Backup database LDDB to Disk='{txtBackup.Text}' With STATS = 1"
Try
con.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = backupQuery
cmd.Connection = con
AddHandler con.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
con.Close()
con.Dispose()
End Try
End Sub
Private Sub BackupForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class

Program sends data but database does not receive it

I have a conundrum.
In my VB.net program, in multiple places I communicate with my SQLserver database. I use Insert, Update and Select statements. My program is made up of multiple forms and my database has 4 tables.
All but one of my subs is working, and despite using break-points and walk through's of the code I can not figure out why.
The form and database tables in question are fine with the select and Insert statements are fully functioning, however the code of the update statement is not. When I run a walk through it behaves as if it has sent the data to the database, however the database never receives it. The connection data is identical to the functioning subs, and the code is in the same format as my update code in other forms within my program. So I can't see why its not working.
Here is the code:
Public selectedDeviceNumber As String = ""
Public selectedDeviceRowNumber As Integer = 0
'================================
'= Set up the DATASETS! =
'================================
Dim PCBconnectionstring As String = "Data Source=ServerName;Initial Catalog=Databasename;User Id=UserId;Password=password;Connect Timeout=30;User INstance=False"
Dim PCBsqlconnection As New SqlClient.SqlConnection(PCBconnectionstring)
Dim damyPCB As New SqlDataAdapter
Dim dsmyPCB As New DataSet
Dim ALcon As New SqlConnection
Dim ALcmd As New SqlCommand
Dim PCBcmd As New SqlCommand
Dim PCBcon As New SqlConnection
'================================
'= SAVE the data! =
'================================
Dim test As String = Me.selectedDeviceNumber
Private Sub SaveToDataBaseFunctionPCB()
'update the data entered to the database
Try
PCBsqlconnection.ConnectionString = "Data Source=ITWIN10-PC\SQL2010;Initial Catalog=SLE1000;User Id=UserId;Password=password;Connect Timeout=30;User Instance=False"
PCBsqlconnection.Open()
PCBcmd.Connection = PCBsqlconnection
PCBcmd.CommandText = "UPDATE PCBlist SET pcbSerial=#pcbSerial,pcbPart=#pcbPart,pcbVent=#pcbVent,pcbDesc=#pcbDesc," & _
"pcbTested=#pcbTested,pcbU1=#pcbU1,pcbU5=#pcbU5,pcbU7=#pcbU7,pcbU10=#pcbU10,pcbU11=#pcbU11,pcbVersion=#pcbVersion," & _
"pcbTestIni=#pcbTestIni,pcbApplyIni=#pcbApplyIni,pcbTestDate=#pcbTestDate,pcbApplyDate=#pcbApplyDate WHERE pcbID=#pcbID "
PCBcmd.Parameters.AddWithValue("#pcbSerial", txtSerialPCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbPart", cboPartPCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbVent", txtVentPCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbDesc", txtDescriptPCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbTested", chkTested1.Checked)
PCBcmd.Parameters.AddWithValue("#pcbU1", txtU11.Text)
PCBcmd.Parameters.AddWithValue("#pcbU5", txtU51.Text)
PCBcmd.Parameters.AddWithValue("#pcbU7", txtU71.Text)
PCBcmd.Parameters.AddWithValue("#pcbU10", txtU101.Text)
PCBcmd.Parameters.AddWithValue("#pcbU11", txtU111.Text)
PCBcmd.Parameters.AddWithValue("#pcbVersion", txtVersionPCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbTestIni", txtTestPCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbApplyIni", txtApplyPCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbTestDate", txtTestDatePCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbApplyDate", txtApplyDatePCB1.Text)
PCBcmd.Parameters.AddWithValue("#pcbID", Me.selectedDeviceNumber)
PCBcmd.ExecuteNonQuery()
PCBcmd.Parameters.Clear()
PCBsqlconnection.Close()
MsgBox("Data updated")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
PCBsqlconnection.Close()
End Try
End Sub
`Private Sub btnAmend_Click(sender As System.Object, e As System.EventArgs) Handles btnAmend.Click
'Save the data to SQL Server
SaveToDataBaseFunctionPCB()
'record activity in Activity Log
FrmSLE1000.txtActivityLogRecorder.Text = ("Data Saved")
'Save the Activity log data to SQL Server
SaveToDataBaseFunction1()
'SLE1000SqlConnection = New SqlConnection(frmConnections.lblDBConnection.Text & frmConnections.lblDBConnection2.Text)
End Sub
If you have any ideas then please let me know. It could be that I've been looking at the code too long and its obvious, however I can't see the problem.
Many thanks
After extensive fiddling with my code I have fixed the problem. As it turns out the problem lay further back in the code. When the Select statement was called it loaded the data into a list view, which you then select a row which you want to edit. The catch ex as exception was being fired at this point, however the data was still being passed to the text boxes so that you could edit the data, so I mentally 'parked' that glitch for later. In solving that glitch the "amend" button and Update function works fine.
If you're interested the original glitch in the code was as follows
Private Sub lvPCB1_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvPCB1.DoubleClick
Dim newmachine As String = FrmSLE1000.txtNo.Text
Try
If lvPCB1.SelectedItems.Count = 0 Then
MessageBox.Show("Ensure that you have selected a PCB Board. Try again.")
Exit Sub
Else
'Set selected units ID number in varable to allow access to all row data to populate tables
selectedDeviceNumber = lvPCB1.SelectedItems(0).Text
PopulateTablesFunctionPCB()
txtSerialPCB1.Text = lvPCB1.SelectedItems(1).Text
'record activity in Activity Log
End If
Catch ex As Exception
MessageBox.Show("Problem with selection")
End Try
End Sub
and the new working code is as follows
Private Sub lvPCB1_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvPCB1.DoubleClick
Dim newmachine As String = FrmSLE1000.txtNo.Text
Try
If lvPCB1.SelectedItems.Count = 0 Then
MessageBox.Show("Ensure that you have selected a PCB Board. Try again.")
Exit Sub
Else
'Set selected units ID number in varable to allow access to all row data to populate tables
selectedDeviceNumber = lvPCB1.SelectedItems(0).Text
PopulateTablesFunctionPCB()
txtSerialPCB1.Text = lvPCB1.SelectedItems(0).Text
'record activity in Activity Log
End If
Catch ex As Exception
MessageBox.Show("Problem with selection")
End Try
End Sub
So it all came down to having a "1" instead of a "0" in the line "txtSerialPCB1.Text = lvPCB1.SelectedItems(0).Text"
And there you have it!

VB.NET Reference new form object's listview from another class

On a form i have a listview with a contextmenu.
Right click on a listview item shows the context menu.
When i click on the menubutton, what i would like to happen is the following :
A form i called TaskLog will appear, it contains only a listview
(This is the code i have) :
Private Sub ShowLogToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowLogToolStripMenuItem.Click
logform = New TaskLog()
logform.task = "taskname"
logform.server = "servername"
logform.Show()
End Sub
That listview should be filled with data from a database before it shows, therefore i have the following in the load event of the TaskLog Form
Public Class TaskLog
Private db As Database = New Database
Public task As String
Public server As String
Private Sub TaskLog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
db.connect()
db.getTaskLog(task, server, Me)
End Sub
End Class
Then in the database class gettask function i call the database, store data in an object, which all works fine. Only problem here is that my database object cannot find the listview and the form, even if i pass the form as a variable to this function (frm as TaskLog).
Public Function getTaskLog(taskname As String, server As String, frm As TaskLog) As Boolean
'Declare sql command variable
Dim command As New SqlCommand
'Try to open db connection
Try
connection.Open()
command.Connection = connection
'Set query to command object text
command.CommandText = "select * from tasklog where ltrim(rtrim(server)) Like'" & Trim(server) & "%' and ltrim(rtrim(task)) = '" & Trim(taskname) & "'"
'Declare data reading pbject
Dim rdr As SqlDataReader = command.ExecuteReader()
'Perform operations while rows are returned from database
While rdr.Read()
'Store database entry to TaskData Object
taskLogData = New TaskData(rdr("frequency").ToString, rdr("start"), rdr("duration"), rdr("delay"), rdr("rescheduled"), rdr("forced"), rdr("task"), rdr("server"), rdr("email"), rdr("message"), rdr("status"), rdr("logtime"))
Dim new_item As New _
ListViewItem(Trim(taskLogData.task_server.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_name.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_status.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_frequency.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_nextrun.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_forced.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_rescheduled.ToString))
new_item.SubItems.Add(Trim(taskLogData.task_rescheduled.ToString))
new_item.Group = frm.ListView1.Groups(Trim(taskData.task_status.ToString))
frm.ListView1.Items.Add(new_item)
End While
Return True
Catch ex As Exception 'If connection fails return error message
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Return True
Finally 'After connection close database
connection.Close()
End Try
End Function
Object Reference not set to an instance of an object appears on the following line in the function above:
frm.ListView1.Items.Add(new_item)
Can someone see the problem, and hopefully some help ? I tried a couple of things but still not sure about what to do best here. Thanks !!!!!!!
This line
new_item.Group = frm.ListView1.Groups(Trim(taskData.task_status.ToString))
refers to a Group that should exist in the ListView1. You could comment it out if it is not needed

Linq-to-SQL SubmitChanges not updating physical database

I am new here and only signed up because I desperately need the solution to my problem. I have a VB.NET project that is using a local .MDF file that I have imported into my project. The primary keys are intact so I know that isn't my issue.
I am using Linq-to-SQL to query the database and make changes. On my main form I use a Data Grid View that is populated by a query. I am having an issue with my insert where the query works fine and the DGV gets updated with newly created data, but when I call SubmitChanges() the changes do not get saved to the actual physical database. I am not sure what I am missing or doing wrong.
Here is my code to better assist your educated answer.
Public Class frmCell_Leader
'Reference DataContext
Private db As New MarquardtClassesDataContext()
Private Sub frmCell_Leader_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
FillProductionGrid()
PrepareInsertFields()
End Sub
Private Sub FillProductionGrid()
''''''''''''''''''''''''''''''''''
'E.Salce Last Modified 11.29.2012
'Comments: Working
''''''''''''''''''''''''''''''''''
'Populate DGV
Dim query = From marq In db.tblProductivities
Select
marq.PartNum, marq.Produced, marq.Packed, marq.Issue, marq.StationNum, _
marq.PlanDownTime, marq.UnplannedDownTime, marq.CurDate
dgvProduction.DataSource = query
End Sub
Private Sub PrepareInsertFields()
''''''''''''''''''''''''''''''''''
'E.Salce Last Modified 11.29.2012
'Comments: Working
''''''''''''''''''''''''''''''''''
'Fill Planned Downtime Combo Box
Dim PlannedQuery = From planned In db.tblPlannedDownTimes
Select planned.Plan_ID, planned.Description, planned.Active
Where Active = True
cboPlanned.DataSource = PlannedQuery
cboPlanned.DisplayMember = "Description"
cboPlanned.ValueMember = "Plan_ID"
'Fill UnPlanned Downtime Combo Box
Dim UnPlannedQuery = From unplanned In db.tblUnplannedDownTimes
Select unplanned.Unplan_ID, unplanned.Description, unplanned.Active
Where Active = True
cboUnplanned.DataSource = UnPlannedQuery
cboUnplanned.DisplayMember = "Description"
cboUnplanned.ValueMember = "UnPlan_ID"
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
'Add the new Production to database
'Create an productivity object
Dim marqpro As New tblProductivity With {
.PartNum = CShort(txtPartNumber.Text),
.Produced = CShort(txtProduced.Text),
.Packed = CShort(txtPacked.Text),
.Issue = txtIssue.Text,
.PlanDownTime = CShort(cboPlanned.SelectedValue),
.UnplannedDownTime = CShort(cboUnplanned.SelectedValue),
.CurDate = Date.Today}
'insert newly created data
Try
'Submit changes too database
db.tblProductivities.InsertOnSubmit(marqpro)
db.SubmitChanges()
db.Refresh(Data.Linq.RefreshMode.KeepCurrentValues, marqpro)
'Refresh DGV
FillProductionGrid()
MessageBox.Show("Data added successfully")
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
End Sub
End Class
Perhaps you have an .mdf file in your project that is getting copied to the bin/debug folder everytime you build.
Why isn't my SubmitChanges() working in LINQ-to-SQL?

Resources