Program sends data but database does not receive it - sql-server

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!

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

DataTable not updating Database with DataAdapter (VB.NET)

*NOTE: I deleted my previous question "Update Database from DataTable and DataAdapter" in place of this one. I have updated the wording and code to be what I am currently testing.
I am trying to update a database with info from a WinForm. I had no issues when using a “normal” SQL update command written by hand (parameters set to the text box values,) but I am trying to clean up and reduce my code and I thought I would bind the controls to a DataTable and use a DataAdapter's update command to achieve the same thing.
I have tried to get various combinations of setting parameters and update commands to work, but the Database is not getting updated from the new DataTable values. I have stepped through the code with each change and can see that the DataTable is getting the new textbox values, but those updates aren’t going to the Database. (This is seen when the Fill_Date block runs and selects all new data from the database.)
Things I’ve tried: Letting the binding get the new values vs. setting the parameters manually. Using the command builder to build the update command, using the .UpdateCommand.ExecuteNonQuery(), command and of course a straight.Update(DataTable) command.
Below is the code that I am using. I am hoping someone can tell me what it is I am doing wrong/missing, or what is the correct path to take. Is there a "best practice" or a better way to do this?
Public Class frmDATA
Dim dt_Test As New DataTable
Dim da_Test As New SqlDataAdapter
Dim SQLcmd As SqlCommand
Private Sub frmDemog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BuildSQL()
Fill_Data()
BindControls()
End Sub
Private Sub frmDemog_Closed(sender As Object, e As EventArgs) Handles Me.Closed
If Not IsNothing(dt_Test) Then dt_Test.Dispose()
If Not IsNothing(da_Test) Then da_Test.Dispose()
If Not IsNothing(SQLcmd) Then SQLcmd.Dispose()
Me.Dispose()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Update_Me()
End Sub
Private Sub BindControls()
txtLName.DataBindings.Add("Text", dt_Test, "Last_Name")
txtFName.DataBindings.Add("Text", dt_Test, "First_Name")
txtAKA.DataBindings.Add("Text", dt_Test, "AKA")
End Sub
Public Sub Update_Me(RefreshSearch As Boolean, RefreshView As Boolean)
Try
Dim testID As Integer = frmTest.dgvSearch.CurrentRow.Cells(0).Value
da_Test.UpdateCommand.Parameters("#ID").Value = testID
da_Test.Update(dt_Test)
Fill_Data()
Catch SqlExceptionErr As SqlException
MsgBox(SqlExceptionErr.Message, vbCritical, "Error")
Catch ex As Exception
MsgBox(ex.Message, vbCritical, "Error")
End Try
End Sub
Public Sub Fill_Data()
Try
dt_Test.Clear()
da_Test.SelectCommand.Parameters("#ID").Value = testID
da_Test.Fill(dt_Test)
Catch SqlExceptionErr As SqlException
MsgBox(SqlExceptionErr.Message, vbCritical, "Error")
Catch ex As Exception
MsgBox(ex.Message, vbCritical, "Error")
End Try
End Sub
Private Sub BuildSQL()
'** Build Selection Query
SQLcmd = New SqlCommand(String.Join(Environment.NewLine,
"SELECT ",
"data_Test.[Last_Name], ",
"data_Test.[First_Name], ",
"data_Test1.[Last_Name] + ', ' + data_Test1.[First_Name] as [AKA] ",
"FROM [DB].data_Test ",
"LEFT JOIN [DB].data_Test as data_Test1 ",
"ON data_Test.[ID] = data_Test1.[AKA_Demog_ID] ",
"WHERE data_Test.[ID]=#ID"
), Vars.sqlConnDB)
SQLcmd.Parameters.Add("#ID", SqlDbType.Int)
da_Test.SelectCommand = SQLcmd
'** Build Update Query
SQLcmd = New SqlCommand(String.Join(Environment.NewLine,
"UPDATE [DB].data_Test SET ",
"[Last_Name] = #LName,",
"[First_Name] = #FName",
"WHERE [ID] = #ID"
), Vars.sqlConnDB)
With SQLcmd.Parameters
.Add("#LName", SqlDbType.NVarChar, 255, "Last_Name") 'Required
.Add("#FName", SqlDbType.NVarChar, 255, "First_Name") 'Required
.Add("#ID", SqlDbType.Int, 0, "ID")
End With
da_Test.UpdateCommand = SQLcmd
End Sub
End Class

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

Update/Edit Database

I know This is something simple yet I cannot do it right or find any answer searching google.
I want to update/edit the data. in the database server, by clicking the data that display on my DataGridView.
below is my sub Edit, the code is not automatically fetching the record to the textbox.
Private Sub btnEdit_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnEdit.Click
Dim transaction As SqlTransaction = Nothing
With New SqlConnection(connectionString)
Try
Call .Open()
transaction = .BeginTransaction()
With .CreateCommand()
.Transaction = transaction
.CommandText = "UPDATE [tbl_info] SET [Name]=#Name WHERE [ID]=#ID;"
With .Parameters
.AddWithValue("ID", txtID.Text)
.AddWithValue("Name", txtName.Text)
End With
Call .ExecuteNonQuery()
Call transaction.Commit()
Call MessageBox.Show("has been update successfully")
End With
Catch ex As Exception
Call transaction.Rollback()
Call MessageBox.Show(ex.Message, "Error")
Finally
Call .Close()
End Try
End With
RefreshData()
Call txtID.Clear()
Call txtName.Clear()
End Sub
On the ExecuteNonQuery line, capture the number of affected rows.
Dim rc As Integer = .ExecuteNonQuery()
If rc comes back as zero we can tell the query ran and found nothing to update.

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