Vb net update statement issue - vb.net-2010

I have vb.net project for insert and update values in SQL server.It has sql code as below:
Public Sub insert_customer_new(ByVal customer_id As Integer, ByVal work_state As Integer)
Dim cmd As New SqlCommand("insert into customer_tbl (customer_id , work_state ) values (#customer_id, #work_state )", conn)
cmd.Parameters.Add("customer_id", SqlDbType.Int).Value = customer_id
cmd.Parameters.Add("work_state", SqlDbType.Int).Value = work_state
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
cmd = Nothing
End Sub
And then
Public Sub update_customer_new(ByVal customer_id As Integer, ByVal work_state As Integer)
Dim cmd As New SqlCommand("update customer_tbl set work_state = #work_state where customer_id = #customer_id ", conn)
cmd.Parameters.Add("customer_id", SqlDbType.Int).Value = customer_id
cmd.Parameters.Add("work_state", SqlDbType.Int).Value = work_state
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
cmd = Nothing
End Sub
I use form Button.Click Event for insert
Private Sub insert_customer_Click(sender As Object, e As EventArgs) Handles insert_customer.Click
If customer_id.Text = String.Empty Then
MsgBox("Pleas Enter Customer Number")
customer_id.Focus()
ElseIf state_txt.Text = String.Empty Then
MsgBox("Pleas Enter The Start State Number ")
state_txt.Focus()
Else
insert_customer_new(customer_id.Text, state_txt.Text)
MsgBox("Insert Done !")
End If
End Sub
And by same way I use form Button.Click Event for update
Private Sub update_state_Click(sender As Object, e As EventArgs) Handles update_state.Click
If customer_id.Text = String.Empty Then
MsgBox("Pleas Enter Customer Number For Update")
customer_id.Focus()
ElseIf state_txt.Text = String.Empty Then
MsgBox("Pleas Enter The New State Number ")
state_txt.Focus()
Else
update_customer_new(customer_id.Text, state_txt.Text)
MsgBox("Update Done !")
End If
End Sub
The problem is some time the update statement does not perform. It gives no error, and the Procedure just skip this line for unknown reasons.
And it's happened about 10% of all cases that performed after application is published.

Related

where should i put the button save codes into this codes that i sent here? because i'd like to save into another table

i put this code because i used combobox and they fill my two textbox,but when try to save its not saving the data that i put
this is the code
Sub loaddata()
Try
reload("SELECT * FROM NAME", STUDENT)
STUDENT.DataSource = dt
STUDENT.DisplayMember = "NAME"
STUDENT.ValueMember = "ID"
Catch ex As Exception
End Try
End Sub
Private Sub NAME_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NAME.SelectedIndexChanged
Try
Dim sql As String
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
strcon.Open()
sql = "SELECT * FROM STUDENT where NAME LIKE '%" & NAME.Text & "%'"
cmd.Connection = strcon
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
GENDER.Text = dt.Rows(0).Item("GENDER").ToString
ADDRESS.Text = dt.Rows(0).Item(" ADDRESS").ToString
End If
Catch ex As Exception
Finally
strcon.Close()
End Try
End Sub
please show me how to put the save codes here,because i use only the BindingNavigator1 to save, but it does not save, sorry if my grammar is wrong because i'm not a fluent in english
I know we have a language barrier but we are both trying our best. I have provided a few examples of code to interact with a database.
It is a good idea to keep you database code separate from you user interface code. If you want to show a message box in you Try code, keep the Try in the user interface code. The error will bubble up from the database code to the calling code.
Using...End Using blocks take care of disposing of database objects. Parameters protect against Sql injection because parameter values are not considered executable code by the database. Note that for OleDb data sources the order that the parameters appear in the sql statement must match the order that they are added to the Parameters collection.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim dt = GetOriginalData()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = dt
End Sub
Private Function GetOriginalData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your first connection string"),
cmd As New OleDbCommand("Select ID, Name From Table1;")
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
InsertData(CInt(ComboBox1.SelectedValue), ComboBox1.SelectedText, txtGender.Text, txtAddress.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub InsertData(id As Integer, name As String, gender As String, address As String)
Using cn As New OleDbConnection("Your second connection string"),
cmd As New OleDbCommand("Insert Into Table2 (ID, Name, Gender, Address) Values (#ID, #Name, #Gender, #Address);", cn)
With cmd.Parameters
.Add("#ID", OleDbType.Integer).Value = id
.Add("#Name", OleDbType.VarChar).Value = name
.Add("#Gender", OleDbType.VarChar).Value = gender
.Add("#Address", OleDbType.VarChar).Value = address
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

System.InvalidOperationException: 'Operation is not valid due to the current state of the object.' on a update query in vb.net

Hello I am trying to do an update query on my database however I end up with this error message
System.InvalidOperationException: 'Operation is not valid due to the current state of the object.'
Here is the code for my search query which I then use in the update
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID = #ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
End Using
Return dt
End Function
This is the ToTextBox function
Public Sub ToTextbox(ByVal newdt)
txtFName.Text = newdt.Rows(0)(1).ToString()
txtLName.Text = newdt.Rows(0)(2).ToString()
mtxtContactNumber.Text = newdt.rows(0)(3).ToString()
txtAddress.Text = newdt.rows(0)(4).ToString()
txtTown.Text = newdt.rows(0)(5).ToString()
txtPostCode.Text = newdt.rows(0)(6).ToString()
End Sub
And the update function
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
con.Open()
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
con.Close()
End Using
Return Result
End Function
And the Update button
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I believe you update problems are solved in comments.
You still have too much stuff in your DataAccess code. Just return the DataTable and use it in the user interface code.
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID = #ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = SearchData(FirstNameTextBox.Text, CInt(IDTextBox.Text))
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
End Sub
Public Sub ToTextbox(ByVal newdt As DataTable)
txtFName.Text = newdt.Rows(0)(1).ToString()
txtLName.Text = newdt.Rows(0)(2).ToString()
mtxtContactNumber.Text = newdt.Rows(0)(3).ToString()
txtAddress.Text = newdt.Rows(0)(4).ToString()
txtTown.Text = newdt.Rows(0)(5).ToString()
txtPostCode.Text = newdt.Rows(0)(6).ToString()
End Sub

Adapter update statement in oledb

I have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

VB.net/MS Access Monthly Donations System Assistance

I'm doing a project for my Database Management subject. I cannot figure out how to add an amount to a previously added amount. For now, I'm only able to update the amount. Here's the code. I'm sorry if I cannot explain it well.
I have 2 forms. My first form allows me to enter a last name and retrieve the data to my list view.
My second form lets me retrieve the data I entered in my first form and it will show up on a separate list view with a "Last Name | Amount" tab.
I have two textboxes. One for last name set to readonly to disable editing, and another for the amount I want to enter.
After entering an amount, let's say 20, it will update on the listview and my database as 20.
The problem is that when I enter a new amount for the same last name, let's say 30, the 30 will replace the 20 but it should be 50 because 20+30 = 50.
I understand the logic and I have tried adding another textbox for addition but I simply do not know the codes for it.
Imports System.Data.OleDb
Public Class Form2
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Israel De Leon\Documents\testing.accdb;"
Dim con As OleDbConnection = New OleDbConnection(conString) 'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb
Dim cmd As OleDbCommand
Dim adapter As OleDbDataAdapter
Dim dt As DataTable = New DataTable()
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'SET LISTVIEW PROPERTIES
ListView1.View = View.Details
ListView1.FullRowSelect = True
'Construct Columns
ListView1.Columns.Add("Last Name", 100)
ListView1.Columns.Add("Amount", 100)
End Sub
Private Sub UpdateLV(lname As String)
'Updates last name and amount entered into the database
Dim sql As String = "UPDATE Table1 SET LastName='" + TextBox1.Text + "',Amount='" + TextBox2.Text + "' WHERE LastName='" + lname + "'"
cmd = New OleDbCommand(sql, con)
'OPEN CON, EXECUTE, UPDATE, CLOSE
Try
con.Open()
adapter = New OleDbDataAdapter(cmd)
adapter.UpdateCommand = con.CreateCommand()
adapter.UpdateCommand.CommandText = sql
If (adapter.UpdateCommand.ExecuteNonQuery() > 0) Then
MsgBox("Successfully Updated")
End If
con.Close()
Retrieve()
ClearBox()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Retrieve()
ListView1.Items.Clear()
'SQL STM
Dim sql As String = "SELECT * FROM Table1 "
cmd = New OleDbCommand(sql, con)
'OPEN CON, RETRIEVE, FILL LISTVIEW
Try
con.Open()
adapter = New OleDbDataAdapter(cmd)
adapter.Fill(dt)
'LOOP THROUGH DT
For Each row In dt.Rows
Populate(row(0), row(1)) 'Index of database row
Next
'CLEAR DATATABLE
dt.Rows.Clear()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Populate(lname As String, aamount As String)
'ROW ARRAY
Dim row As String() = New String() {lname, aamount}
Dim item As ListViewItem = New ListViewItem(row)
'ADD TO ROWS COLLECTION
ListView1.Items.Add(item)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Retrieve()
End Sub
Private Sub ListView1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView1.MouseClick
Dim llname As String = ListView1.SelectedItems(0).SubItems(0).Text
Dim amounts As String = ListView1.SelectedItems(0).SubItems(1).Text
TextBox1.Text = llname
TextBox2.Text = amounts
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim amounts As String = ListView1.SelectedItems(0).SubItems(0).Text
UpdateLV(amounts)
End Sub
Private Sub ClearBox()
TextBox1.Text = ""
TextBox2.Text = ""
End Sub
End Class
Mathematical operation should not be done using strings. This is a real basic principle that many VB.NET programmers don't think enough thanks to the forgiveness allowed by Option Strict Off in the VB.NET project settings.
If you are just starting a new project in VB.NET don't use this setting but switch it ASAP to On. This will give you an halt when you try to use strings as they were numbers and force you to do the appropriate conversion and checking on the values provided.
So your code that updates the amount rewritten
Private Sub UpdateLV(lname As String)
' Get the amount as a number (decimal for currency is the best)
Dim addAmt As Decimal
if Not decimal.TryParse(textbox2.Text, addAmt) Then
MessageBox.Show("Insert a valid amount please")
return
End If
' Sanity check
if addAmt <= 0 Then
MessageBox.Show("Amount should be > 0")
return
End If
'Updates last name and amount entered into the database
Dim sql As String = "UPDATE Table1 SET LastName=#name
,Amount=Amount+#amt
WHERE LastName=#oldname"
cmd = New OleDbCommand(sql, con)
Try
con.Open()
' Using an adapter here is wrong. You use directly the command
cmd.Parameters.Add("#name", OleDbType.VarWChar).Value = textBox1.Text
cmd.Parameters.Add("#amt", OleDbType.Decimal).Value = addAmt
cmd.Parameters.Add("#oldname", OleDbType.VarWChar).Value = lName
If (cmd.ExecuteNonQuery() > 0) Then
MsgBox("Successfully Updated")
End If
con.Close()
Retrieve()
ClearBox()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Something else is not clear in your code. What is the purpose of changing also the LastName here? Finally do not keep a global connection object. Instead create it when you need it and destroy it afterward with Using statement. It will be better for your memory footprint and for your database

Update a database record

I use following code to update database record after retrieving data to the text boxes via a datagridview.
But this gives me an exception as object reference not set to an instance of the object. Please help
Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridViewUserType.CellClick
Dim i As Integer
i = DataGridViewUserType.CurrentRow.Index
If i >= 0 Then
Me.txtBoxID.Text = DataGridViewUserType.Item(0, i).Value
Me.txtBoxUserType.Text = DataGridViewUserType.Item(1, i).Value
Else
MessageBox.Show("Empty Row Clicked")
End If
End Sub
Private Sub btnUserTypeUpdate_Click(sender As Object, e As EventArgs) Handles btnUserTypeUpdate.Click
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.User_Type SET Type = #tp WHERE Type_ID = #ID"
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text)
cmd.Parameters.AddWithValue("#tp", txtBoxUserType.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Successfully Updated")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Update Records")
Finally
con.Close()
btnUserTypeSave.Show()
txtBoxID.Clear()
txtBoxUserType.Clear()
End Try
End Sub
Thankz Fabio
The error was with "cmd"
I just put Dim cmd As SqlCommand = New SqlCommand before using it and now it is functioning.
Thankz All