I have a form which contains a ComboBox linked to an access database. I am asking the combobox to display the Incident ID, Supplier and Supply date of all records in the database table
The code is as follows
Private Sub frm_5_UpdateIncidentSelect_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Links dropdown menu to incident table in database
Dim dt As New DataTable
Dim query As String = "select [incident ID],[stock supplier],[supply date] from incident"
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database.accdb")
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
Dim MyDataRow As DataRow = dt.Rows(0)
Dim x As Integer
x = dt.Rows.Count
For y = 0 To x
If y < x Then
MyDataRow = dt.Rows(y)
ComboBox1.Items.Add(CStr(MyDataRow("Incident ID")))
ComboBox1.Items.Add(CStr(MyDataRow("stock supplier")))
ComboBox1.Items.Add(CStr(MyDataRow("supply date")))
End If
Next
End Sub
The issue I am having is that the data is being returned over 3 lines as follows
12
Supplier1
01/01/2015
13
Supplier2
07/01/2015
Ideally I need this information returned on one as follows
12 Supplier 1 01/01/2015
13 Supplier 2 07/01/2015
I cannot for the life of me figure this out, I am not great with VB I am afraid. Can anyone tell me where I am going wrong?
Here's an example of what Plutonix was talking about:
Public Class frm_5_UpdateIncidentSelect
Private Class ComboBoxData
Public IncidentID As String
Public StockSupplier As String
Public SupplyDate As String
Public Sub New(ByVal data As DataRow)
Me.IncidentID = data("Incident ID").ToString
Me.StockSupplier = data("stock supplier").ToString
Me.SupplyDate = data("supply date").ToString
End Sub
Public Overrides Function ToString() As String
Return Me.IncidentID.PadRight(5, " ") & " Supplier " & Me.StockSupplier.PadRight(5, " ") & " " & Me.SupplyDate
End Function
End Class
Private Sub frm_5_UpdateIncidentSelect_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Links dropdown menu to incident table in database
Dim dt As New DataTable
Dim query As String = "select [incident ID],[stock supplier],[supply date] from incident"
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database.accdb")
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
For Each Data As DataRow In dt.Rows
ComboBox1.Items.Add(New ComboBoxData(Data))
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedIndex <> -1 Then
Dim data As ComboBoxData = DirectCast(ComboBox1.SelectedItem, ComboBoxData)
Debug.Print(data.IncidentID)
Debug.Print(data.StockSupplier)
Debug.Print(data.SupplyDate)
End If
End Sub
End Class
It's been over 5 years, but I hope it can help someone.
The solution is actually way, way easier.
I had the same problem while coding a simple Programm for internal use.
Try this:
For i As Integer = 0 To dataSet.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dataSet.Tables(0).Rows(i)(0) + " | " +
dataSet.Tables(0).Rows(i)(1) + " | " + dataSet.Tables(0).Rows(i)(2))
Next
Related
The following code is supposed to display information from a database but there is an error (the title of this question) on the DBCmd.ExecuteNonQuery() line of code.
Does anyone know how I can resolve this problem?
• I am using VB.NET
• I am using an Access database
The code is:
Imports System.Data.OleDb
Public Class frmCheckAvailablity
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Access As New DBControl
Dim QRY As String
Private DBCmd As OleDbCommand
Dim DBDR As OleDbDataReader
Public DBDA As New OleDbDataAdapter("SELECT RoomType FROM tblRoomBookings", DBCon)
Public DT As New DataTable
Public DS As New DataSet
Public DR As DataRow
Private Function NotEmpty(text As String) As Boolean
Return Not String.IsNullOrEmpty(text)
End Function
Private Sub frmCheckAvailability_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'RUN QUERY
Access.ExecQuery("SELECT * FROM tblRoomBookings ORDER BY BookingID ASC")
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub frmCheckAvailability_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'NewHotelDataSet.tblRoomBookings' table. You can move, or remove it, as needed.
Me.TblRoomBookingsTableAdapter.Fill(Me.NewHotelDataSet.tblRoomBookings)
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub Search()
DBDA.Fill(DT)
txtSearch.AutoCompleteCustomSource.Clear()
For Each DBDR In DT.Rows
txtSearch.AutoCompleteCustomSource.Add(DBDR.Item(0).ToString)
Next
txtSearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub
Private Sub SearchCustomers(RoomType As String)
'ADD PARAMETERS & RUN QUERY
Access.AddParam("#RoomType", "%" & RoomType & "%")
Access.ExecQuery("SELECT * FROM tblRoomBookings WHERE RoomType LIKE #RoomType")
'REPORT & ABORT ON ERRORS
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType'" & txtSearch.Text & "'"
DBCmd = New OleDbCommand(QRY, DBCon)
DBCmd.ExecuteNonQuery()
DBDR = DBCmd.ExecuteReader
If DBDR.Read Then
txtRoomType.Text = DBDR("RoomType")
txtFirstNight.Text = DBDR("FirstNight")
txtLastNight.Text = DBDR("LastNight")
txtNoNights.Text = DBDR("NoNights")
End If
End Sub
The only place in the code that I see DBcmd.ExecuteNonQuery is in search text changed event. Do really want to run this code every time the users types a letter?
Do not create a new connection at the class (Form) level. Every time the connection is used it needs to be disposed so it can be returned to the connection pool. Using...End Using blocks handle this for you even if there is an error.
Don't call .ExecuteNonQuery. This is not a non query; it begins with Select.
You can't execute a command without an Open connection.
Never concatenate strings for sql statments. Always use parameters.
The connection is open while the reader is active. Don't update the user interface while the connection is open.
Load a DataTable and return that to the user interface code where you update the user interface.
Private ConStr As String = "Your connection string"
Private Function GetSearchResults(Search As String) As DataTable
Dim dt As New DataTable
Dim QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType = #Search"
Using DBcon As New OleDbConnection(ConStr),
DBCmd As New OleDbCommand(QRY, DBcon)
DBCmd.Parameters.Add("#Search", OleDbType.VarChar).Value = Search
DBcon.Open()
Using reader = DBCmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
Dim dtSearch = GetSearchResults(txtSearch.Text)
If dtSearch.Rows.Count > 0 Then
txtRoomType.Text = dtSearch(0)("RoomType").ToString
txtFirstNight.Text = dtSearch(0)("FirstNight").ToString
txtLastNight.Text = dtSearch(0)("LastNight").ToString
txtNoNights.Text = dtSearch(0)("NoNights").ToString
End If
End Sub
I have linked an Access database to my program. It populates the DataGridView as it is intended to so that part of the program works. However the new data that i add to my DataGridView wont show up and I don't know what is wrong with my code.
Can anyone see anything wrong or something I've missed out that would cause the code not to function as desired? Thank you in advance :)
Imports System.Data.OleDb
Public Class Form1
Dim j As OleDbConnection
Dim a As OleDbDataAdapter
Dim s As DataSet
Dim lokasidb As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call jaringan()
a = New OleDbDataAdapter("Select * From datadairy", j)
s = New DataSet
s.Clear()
a.Fill(s, "datadairy")
DataGridDairy.DataSource = (s.Tables("datadairy"))
End Sub
Private Sub eksekusiSql(ByVal Sql As String)
Dim objcmd As New System.Data.OleDb.OleDbCommand
Call jaringan()
Try
objcmd.Connection = j
objcmd.CommandType = CommandType.Text
objcmd.CommandText = Sql
objcmd.ExecuteNonQuery()
objcmd.Dispose()
MsgBox("The new data successfully saved", vbInformation)
Catch ex As Exception
MsgBox("The new data is failed to save", vbInformation)
End Try
End Sub
Sub jaringan()
lokasidb = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\19106060045_Tugas Modul 5.accdb"
j = New OleDbConnection(lokasidb)
If j.State = ConnectionState.Closed Then j.Open()
End Sub
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Dim No As String = TextNo.Text
Dim Jenis_Susu_Sapi As String = TextSusu.Text
Dim Jenis_Olahan As String = TextOlahan.Text
Dim Harga_per_kg As String = TextHarga.Text
Dim Tempat_Penjualan As String = TextPasar.Text
Dim Sql_Simpan_Dairy As String = "Insert into datadairy (No, Jenis_Susu_Sapi, Jenis_Olahan, Harga_per_kg, Tempat_Penjualan) values (" + No + ",'" + Jenis_Susu_Sapi + "','" + Jenis_Olahan + "','" + Harga_per_kg + "','" + Tempat_Penjualan + "')"
eksekusiSql(Sql_Simpan_Dairy)
ShowDairydata()
End Sub
Public Sub ShowDairydata()
Call jaringan()
a = New OleDbDataAdapter("Select * from datadairy", j)
s = New DataSet
s.Clear()
a.Fill(s, "datadairy")
DataGridDairy.DataSource = (s.Tables("datadairy"))
End Sub
After adding new data to your database, just use
'DataGridDairy.Databind()'
to refresh.
Private Sub Charges()
Dim Query As String
Query = "Select * from Charges where DOctype='" & comboBoxTranType.Text & "'"
Dim cmd As New SqlCommand(Query, con)
con.Open()
Dim dataAdapter As New SqlDataAdapter(Query, con)
Dim dt As New DataTable
dataAdapter.Fill(dt)
dataAdapter.Dispose()
If dt.Rows.Count > 0 Then
LabelV001.Text = dt.Rows(0).Item("Head").ToString()
LabelV002.Text = dt.Rows(1).Item("Head").ToString()
LabelV003.Text = dt.Rows(2).Item("Head").ToString()
End If
If dt.Rows.Count > 0 Then
LabelFIELD1.Text = dt.Rows(0).Item("Equation").ToString()
LabelFIELD2.Text = dt.Rows(1).Item("Equation").ToString()
LabelFIELD3.Text = dt.Rows(2).Item("Equation").ToString()
End If
con.Close()
End Sub
SIR WITH YOUR HELP I GOT THE RESULT BEFORE, BUT CAUSE OF ERROR FOR FIELDTEXT3 i.e There is no row at position 2, equation 3 cannot be calculated, pls help me out,
Not sure why they were so quick to close your new question...I was building an answer for it.
Click on Project --> Add Reference
Switch to the COM option
Select the "Microsoft Script Control 1.0" entry and click OK.
Now you can use code like below, creating code for textCharges1 --> V001 through textCharges25 --> V025:
Public Class Form1
Private SC As New MSScriptControl.ScriptControl
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SC.Language = "VBScript"
Dim ctl As Control
Dim ctlName, functionBody As String
functionBody = "Function {0}()" & vbCrLf & vbTab & "{0} = CDbl({1}.Text)" & vbCrLf & "End Function"
For i As Integer = 1 To 25
ctlName = "textCharges" & i
ctl = Me.Controls.Find(ctlName, True).FirstOrDefault
If Not IsNothing(ctl) Then
SC.AddObject(ctlName, ctl, True)
SC.AddCode(String.Format(functionBody, "V" & i.ToString("000"), ctlName))
End If
Next
LABELFIELD2.Text = "V001*V002/100"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim result = SC.Eval(LABELFIELD2.Text)
lblResult.Text = result
Catch ex As Exception
lblResult.Text = "{Error}"
End Try
End Sub
End Class
Running example:
i am making a stock management system as part of my college project. i have a search bar and the result is outputted into a listbox. when the searched product is clicked the user will be taken to a new form where they will be able to view product information such as product name, price, quantity, stock. Also the user can delete and add stock. I have provided a screenshot of how it will look below.
I'm new to Visual Studio, my problem is that i am unsure how to display the product information into the textbox, can someone please help.
This is my code so far in Form4, which is the homepage that contains the search result and listbox.
'Importing System.Data.OleDb, this is needed for connection with database and is needed for database requirements.
Imports System.Data.OleDb
'This is the homepage
Public Class FrmHomePage
'this code runs when the user searches for a certain product - " the search button event"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
'The code below is used to open the database connection.
Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblProduct WHERE productID LIKE '" & txtSearch_Bar.Text & "'", con)
con.Open()
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
'This if statement makes sure that the product the user is searching for is inside the database, if it isnt then a "no matches" message is displayed.
If Not sdr.HasRows Then
MessageBox.Show("No Matches")
Exit Sub
End If
'this clears the listbox so, if the user searches same product again, it wouldn't duplicate.
lstbSearchResult.Items.Clear()
'Checking for the item in database and outputting it to the listbox.
While (sdr.Read())
lstbSearchResult.Items.Add(sdr("ProductID"))
End While
'closing the database connection
con.Close()
End Sub
'this private sub is basically a side menu which slides out when the user clicks the button "menu".
'Inside the menu the user will have different options such As settings, About us, And more.
Private Sub btnMenu_Click(sender As System.Object, e As System.EventArgs) Handles btnMenu.Click
PnlSide_Menu.Location = New Point(-183, 0)
Do Until PnlSide_Menu.Location.X = -10
PnlSide_Menu.Location = New Point(PnlSide_Menu.Location.X + 1, 0)
Loop
Do Until PnlSide_Menu.Location.X = 0
PnlSide_Menu.Location = New Point(PnlSide_Menu.Location.X + 1, 0)
Refresh()
System.Threading.Thread.Sleep(20)
Loop
End Sub
'private sub for closing the the side menu/side bar.
Private Sub BtnBack_Click(sender As System.Object, e As System.EventArgs) Handles BtnBack.Click
PnlSide_Menu.Location = New Point(0, 0)
Do Until PnlSide_Menu.Location.X = -170
PnlSide_Menu.Location = New Point(PnlSide_Menu.Location.X - 1, 0)
Refresh()
Loop
Do Until PnlSide_Menu.Location.X = -183
PnlSide_Menu.Location = New Point(PnlSide_Menu.Location.X - 1, 0)
System.Threading.Thread.Sleep(20)
Loop
End Sub
'this is the logout button function.
'when clicked the user will be taken back to the login page.
Private Sub btnLogOut_Click(sender As Object, e As EventArgs) Handles btnLogOut.Click
Me.Close()
FrmLogin.Show()
End Sub
Private Sub lstbSearchResult_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstbSearchResult.SelectedIndexChanged
End Sub
This code below is where i am planning to do the things mentioned above.
'Click event of the result in listbox.
Private Sub lstbSearchResult_Click(sender As Object, e As EventArgs) Handles lstbSearchResult.Click
Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblProduct WHERE productID LIKE '" & txtSearch_Bar.Text & "'", con)
con.Open()
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
con.Close()
frmProductForm.Show()
End Sub
End Class
I put my explanations in with the code.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
'The code below is used to open the database connection.
'Change Dim to Using - this takes care of disposing of objects you create with the End Using
Using con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
'You download every field in the table but you only use the productID field
'the idea with database communication is to get in and out as quickly as possible
'only ask for the data you need
'Your user is actually typing in and searching for a productID?
'A productID in a database is usually an Integer of a Long
'Check what datatype this is. If this is a number, what does it mean to find a number LIKE another number?
Using cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblProduct WHERE productID LIKE '" & txtSearch_Bar.Text & "'", con)
con.Open()
Using sdr As OleDbDataReader = cmd.ExecuteReader()
'This if statement makes sure that the product the user is searching for is inside the database, if it isnt then a "no matches" message is displayed.
If Not sdr.HasRows Then
MessageBox.Show("No Matches")
Exit Sub
End If
'this clears the listbox so, if the user searches same product again, it wouldn't duplicate.
lstbSearchResult.Items.Clear()
'Checking for the item in database and outputting it to the listbox.
While (sdr.Read())
'Use a class to hold all your Product data
Dim p As New Product
p.ProductID = sdr.GetInt32(0) 'I am just guessing at the order of your fields
p.ProductName = sdr.GetString(1)
p.Price = sdr.GetDouble(2)
p.Section = sdr.GetInt32(3)
p.Supplier = sdr.GetString(4)
lstbSearchResult.Items.Add(p)
End While
End Using
End Using
'closing the database connection
con.Close()
End Using
End Sub
'Click event of the result in listbox.
Private Sub lstbSearchResult_Click(sender As Object, e As EventArgs) Handles lstbSearchResult.Click
'Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
'Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblProduct WHERE productID LIKE '" & txtSearch_Bar.Text & "'", con)
'con.Open()
'Dim sdr As OleDbDataReader = cmd.ExecuteReader()
'con.Close()
'You just got all this info in Button1.Click
'and it is all saved in your list box
frmProductForm.Show()
Dim p As Product = DirectCast(lstbSearchResult.SelectedItem, Product)
frmProductForm.txtProductName.Text = p.ProductName 'The names of the text boxes are guesses
frmProductForm.txtProductID.Text = p.ProductID
'etc.
End Sub
End Class
Public Class Product
Public Sub New()
'Default constructor
End Sub
Public Sub New(intProductID As Integer, strProductName As String, dblPrice As Double, intCurrentStock As Integer, intSection As Integer, strSupplier As String)
ProductID = intProductID
ProductName = strProductName
Price = dblPrice
CurrentStock = intCurrentStock
Section = intSection
Supplier = strSupplier
End Sub
Private _ProductID As Integer
Public Property ProductID As Integer
Get
Return _ProductID
End Get
Set(value As Integer)
_ProductID = value
End Set
End Property
Private _ProductName As String
Public Property ProductName As String
Get
Return _ProductName
End Get
Set(value As String)
_ProductName = value
End Set
End Property
Private _Price As Double
Public Property Price As Double
Get
Return _Price
End Get
Set(value As Double)
_Price = value
End Set
End Property
Private _CurrentStock As Integer
Public Property CurrentStock As Integer
Get
Return _CurrentStock
End Get
Set(value As Integer)
_CurrentStock = value
End Set
End Property
Private _Section As Integer
Public Property Section As Integer
Get
Return _Section
End Get
Set(value As Integer)
_Section = value
End Set
End Property
Private _Supplier As String
Public Property Supplier As String
Get
Return _Supplier
End Get
Set(value As String)
_Supplier = value
End Set
End Property
Public Overrides Function ToString() As String 'This is what the list box calls to get what to put in its text
Return $"{_ProductID} {_ProductName}"
End Function
End Class
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