Problem with syntax, code works fine in a different area of my project. VB.NET - sql

So I am trying to update a database and a datagridview with a "save" button, I used the part of this code earlier in my program for another function, but here it is giving me a syntax error. Can anyone tell me where? I don't understand where it is.
This part of the code works when I add an employee.
Private Sub AddEmployee_Click(sender As Object, e As EventArgs) Handles AddEmployee.Click
Dim Msg, Style, Title, Response, mystring
Msg = "Do you want to add employee ?"
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "MsgBox Demonstration"
' Display message.
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
TableAdapterManager.UpdateAll(Database13DataSet)
con.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert INTO dbo.employees (EmpID, LastName, FirstName, AddressHalf, SSN, VehNumb, Certification) values ('" + EmpID.Text + "' , '" + LastName1.Text + "', '" + FirstName1.Text + "', '" + AddyHalf1.Text + "', '" + SocialNum.Text + "', '" + VehNumb.Text + "', '" + Certification1.Text + "')"
cmd.Connection = con
cmd.ExecuteNonQuery()
MessageBox.Show("Employee Added")
Else
mystring = True
MessageBox.Show("Cancelled")
End If
con.Close()
This part of the code is the part that doesn't work. I think it has something to do with my coding trying to update a table but I cannot figure it out.
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim Msg, Style, Title, Response, mystring
Msg = "Do you want to update employee ?"
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "MsgBox Demonstration"
' Display message.
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
TableAdapterManager.UpdateAll(Database13DataSet)
con.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Update employees SET (EmpID, LastName, FirstName, AddressHalf, SSN, VehNumb, Certification) Where ( ModEmpID.Text , ModLastName.Text , ModFirstName.Text, ModAddy.Text , ModSSN.Text , ModVehNum.Text , ModCerts.Text )"
cmd.Connection = con
cmd.ExecuteNonQuery()
MessageBox.Show("Employee Added")
con.Close()
Else
mystring = True
MessageBox.Show("Cancelled")
End If
con.Close()
End Sub
Public Sub Updating()
Me.EmployeesTableAdapter.Fill(Me.Database13DataSet.Employees)
End Sub
End Class

If Response = vbYes Then
TableAdapterManager.UpdateAll(Database13DataSet)
con.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert INTO dbo.employees (EmpID, LastName, FirstName, AddressHalf, SSN, VehNumb, Certification) values ('" + EmpID.Text + "' , '" + LastName1.Text + "', '" + FirstName1.Text + "','" + AddyHalf1.Text + "', '" + SocialNum.Text + "', '" + VehNumb.Text + "', '" + Certification1.Text + "')"
cmd.Connection = con
cmd.ExecuteNonQuery()
MessageBox.Show("Employee Added")
Else
Nooo.
It doesn't work like that; it was specifically intended not to work like that
You have tableadapters; nowhere at all, ever, in any of your code should there be "INSERT INTO.. or "UPDATE .., select, delete or any other kind of SQL
Let's have a real quick back-to-basics
At some point you've followed some tutorial that probably had you do something that caused a XyzDataSet.xsd file to appear in your project. Inside it there are datatables and tableadapters and the whole thing looks kinda like a database.
It's a local representation of a database; the table adapters download data from the database into the dataset's datatables; you manipulate the data/show the user/change it/add to it/delete from it..
..and when you're done you call upon the tableadapter to push it back to the database.
TableAdapters know how to do all that stuff you've put in your code; you can open the XyzDataSet.Designer.vb file and see it; it has thousands of lines of code intended for pulling and pushing a database
If you reach a point where you think "I don't actually have a facility for... downloading all the employees called smith" then you go to your dataset, you find the employees table adapter, you right click it and you Add Query.. SELECT * FROM employees WHERE name like #name, you call it FillByName, you finish the wizard, and suddenly your employeeTableAdapter has a new method called FillByName that takes a datatable and a string name. You call it like eta.FillByName(myXyzDataset.Employees, "Smith") - it does all the databasey bit for you, the command, the parameters, the connection..
You want to add a new employee; again it's dead easy and the tableadapter will save it, you just have to put the new emp into the local datatable:
Dim emp = myXyzDataSet.Employees.NewEmployeeRow()
emp.Name = "John Smith"
emp.Age = 23
...
myXyzDataSet.Employees.AddEmployeeRow(emp)
There's a shortcut if you know all the values:
myXyzDataSet.Employees.AddEmployeeRow("John Smith", 23, ...)
Either way your local data cache, the datatable, now contains a new record that needs saving. That's done with:
employeeTableAdapter.Update(myXyzDataSet.Employees)
The TA will look at the row and see it has been recently added. It will run the INSERT command it has built in - you don't need to do it
If you had edited a row:
Dim r = myXyzDataSet.Employees(0) 'first one.. or maybe you'll loop and find John Smith, or use the Find method..
r.Name = "Joe Smith"
Then the row knows it has been altered. The tableadapter will know it too, and when you call Update (think of it like Save, it's not just for SQL UPDATE) it will fire the built in UPDATE command and save the name change back to the DB.
Happens similarly for DELETE..
TableAdapters are the devices that pull and push data. If you want to add custom SQLs to your app, add them to the TAs and call the methods. Don't fill your code with direct use of db commands

I finally figured it out after another hour...
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim Msg, Style, Title, Response, mystring
Msg = "Do you want to update employee ?"
Style = vbYesNo + vbCritical + vbDefaultButton2
Title = "MsgBox Demonstration"
' Display message.
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
DataGridView1.CurrentRow.Cells(0).Value = Me.ModEmpID.Text
DataGridView1.CurrentRow.Cells(1).Value = Me.ModLastName.Text
DataGridView1.CurrentRow.Cells(2).Value = Me.ModFirstName.Text
DataGridView1.CurrentRow.Cells(3).Value = Me.ModAddy.Text
DataGridView1.CurrentRow.Cells(4).Value = Me.ModSSN.Text
DataGridView1.CurrentRow.Cells(5).Value = Me.ModVehNum.Text
DataGridView1.CurrentRow.Cells(6).Value = Me.ModCerts.Text
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim cmd4 As New SqlCommand("", con)
cmd4.CommandText = "update Employees set LastName ='" & DataGridView1.Rows(i).Cells(1).Value & "' , FirstName= '" & DataGridView1.Rows(i).Cells(2).Value & "' , AddressHalf = '" & DataGridView1.Rows(i).Cells(3).Value & "' , SSN = '" & DataGridView1.Rows(i).Cells(4).Value & "' , VehNumb = '" & DataGridView1.Rows(i).Cells(5).Value & "' , Certification = '" & DataGridView1.Rows(i).Cells(6).Value & "'Where EmpID = '" & DataGridView1.Rows(i).Cells(0).Value & "' "
con.Open()
cmd4.ExecuteNonQuery()
con.Close()
Next
MessageBox.Show("Employee Updated")
Else
mystring = True
MessageBox.Show("Cancelled")
End If
con.Close()
End Sub

Related

Binding Source doesn't work on column names with two or more words in DataGridView

Dim bagentdata As New BindingSource
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim SQL As String
Private Sub frmAgent_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
'conn.Open()
ConnectDatabase()
SQL = ""
SQL = "SELECT ID, Name `Agent Name`, Address, Pincode, ContactNo, AltContactNo, SelfIPType, SelfIPRef, SelfIPA, SelfIPP, " & _
"IsIPOPD, IPOPDType, IPOPDValue, IsActive, CreatedBy, CreatedOn FROM tblagentmaster"
myCommand.Connection = Conn
myCommand.CommandText = SQL
myAdapter.SelectCommand = myCommand
myData.Clear()
myAdapter.Fill(myData)
Me.AgentDataView.DataSource = myData
Me.AgentDataView.DefaultCellStyle.Font = New Font("Arial", 10, FontStyle.Bold)
AgentDataView.ReadOnly = True
CloseDatabase()
Catch myerror As MySqlException
MessageBox.Show("Error: " & myerror.Message)
End Try
Clear.PerformClick()
End Sub
Private Sub Search_TextChanged(sender As Object, e As EventArgs) Handles Search.TextChanged
bagentdata.DataSource = myData
AgentDataView.DataSource = bagentdata
bagentdata.Filter = "[Agent Name] Like '%" & Search.Text & "%' " & _
" OR ContactNo = " & Val(Search.Text) & " OR ID = " & Val(Search.Text)
If Search.Text = "" Then
Clear.PerformClick()
End If
End Sub
Filter by Agent Name is not working, please anyone need help on this. Filter by ID or Contactno is working fine. I have a similar kind of code in another form, there it's working fine.
Edit: Even if I change the SQL = "SELECT ID, Name, Address, Pincode, ContactNo, AltContactNo, SelfIPType, SelfIPRef, SelfIPA, SelfIPP, IsIPOPD, IPOPDType, IPOPDValue, IsActive, CreatedBy, CreatedOn FROM tblagentmaster"
and Filter Text as bagentdata.Filter = "Name Like '%" & Search.Text & "%' " then also Filter By Name not working.
Below adding another Sample code where the Filter is working perfectly:
Sub ClearAll(rindex As Integer)
Try
ConnectDatabase()
SQL = ""
SQL = "SELECT BillNo as BillNO, date(CaseCreatedOn) as 'Booked On', PatientName as `Patient Name` , UHID, PatientAge as Age, PatientSex as Gender FROM tblbooking " & _
"where BillNo in (SELECT DISTINCT BillNo FROM tblbookingdetails WHERE ItemStatus in (7,8)) ORDER BY 'Booked On', BillNO"
myCommand.Connection = Conn
myCommand.CommandText = SQL
myAdapter.SelectCommand = myCommand
myData.Clear()
myAdapter.Fill(myData)
allbilldtv.DataSource = myData
CloseDatabase()
Catch myerror As MySqlException
MessageBox.Show("Error: " & myerror.Message)
End Try
Try
allbilldtv.CurrentCell = allbilldtv.Rows(rindex).Cells(0)
allbilldtv_CellClick(Nothing, Nothing)
Catch err As ArgumentOutOfRangeException
MessageBox.Show("Report Generate Queue All Cleared...!!!", "©2022-25 Healeon™ - All Rights Reserved®", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
Private Sub CommonSearch_TextChanged(sender As Object, e As EventArgs) Handles CommonSearch.TextChanged
Try
allbilldata.DataSource = myData
allbilldtv.DataSource = allbilldata
allbilldata.Filter = "[Patient Name] Like '%" & CommonSearch.Text.ToUpper & "%' OR BillNO = " & Val(CommonSearch.Text)
If CommonSearch.Text = "" Then
ClearAll(0)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
According to the documentation for BindingSource.Filter (here):
If the underlying data source is a DataSet, DataTable, or DataView,
you can specify Boolean expressions using the syntax documented for
the DataColumn.Expression property.
Then according to the documentation for DataColumn.Expression (here):
When you create an expression, use the ColumnName property to refer to
columns.
I would suggest doing this following:
Setup a breakpoint when filling the DataTable's data
Step over (F10 shortcut key) to the next line
Inspect the Columns property of the DataTable
What I suspect is happening is that the Fill method is massaging the column name to conform to proper naming convention, e.g. "Agent Name" becomes "AgentName". Once you have the actual name of the DataColumn, use it in your filter.

vb.net how to display Selected data from postgresql?

why is it even though i declared correctly the database name and its table, the error always saying TracingApp_fmemployeesuppliersfeedbackquestions is not exists, I just want that if the firstname and lastname exist in the database the record of that i search will show in the DataGridView1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim firstname = firstnametextbox.Text.Trim()
Dim lastname = lastnametextbox.Text.Trim()
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=contacttracing;server=localhost;port=5432;uid=*****;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT firstname= '" & firstname & "', lastname= '" & lastname & "' FROM TracingApp_fmemployeesuppliersfeedbackquestions ", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
DataGridView1.DataSource = dt
End Sub
Here is my postgresql tree
this is the error i get
UPDATE
ive tried this also
Odbc.OdbcCommand("SELECT firstname= '" & firstname & "', lastname= '" & lastname & "' FROM public.TracingApp_fmemployeesuppliersfeedbackquestions ", MyCon)
it didnt work also...
I suggest to surround the table name in quotes:
"SELECT * FROM ""TracingApp_fmemployeesuppliersfeedbackquestions"" "
"" being what one uses to get a single " into a VB string
I suggest this because I'm aware that PG converts all non quoted table names to lowercase (as can be seen in your "relation does not exist" error message) but the query tool tree shows that some letters in the table names are upper case, so I suspect the table names were created as case sensitive, and TracingApp_fmemployeesuppliersfeedbackquestions is different to tracingapp_fmemployeesuppliersfeedbackquestions
It might be less annoying for you to change your table names, if no other app is using the database, so you don't have to fill your VB strings up with lots of ""

Update Access database using Visual Studio 2015 - VB.net

I am trying to do a simple update to an Access 2016 database. I am using Visual Studio/VB.net. I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore). I have tried two different ways to do this...using the update table adapter, for example:
MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
AvailabilityTextBox.Text, EmailTextBox.Text)
Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
But this method gives me the error of Syntax Error in UPDATE statement. Again I have used this method elsewhere with no problems. Below I will post all the code for this form.
Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class editMediators
Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")
' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
Dim cmd As New OleDbCommand
connect() ' open our connection
Try
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
MsgBox("Data Has Been Saved !", vbInformation)
Catch ex As Exception
MsgBox("Error when saving data: " & ex.Message)
End Try
End Sub
Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
DateTimePicker1.Value = Today()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
NewData = True
alertMsgBox2()
End Sub
Private Sub alertMsgBox2()
Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
"No: Exits the mediator update window without saving," & vbNewLine &
"Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
Case MsgBoxResult.Yes
MediatorsListBindingSource.EndEdit()
updateMediator()
'intentionally commented out
'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
'AvailabilityTextBox.Text, EmailTextBox.Text)
' Me.Close()
Case MsgBoxResult.No
MediatorsListBindingSource.CancelEdit()
Me.Close()
End Select
End Sub
Private Sub updateMediator()
Dim saveInfo As String
If NewData Then
Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
If Message = vbNo Then
Exit Sub
End If
Try
'Update mediator information
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
Catch ex As Exception
End Try
Else
Exit Sub
End If
runAccessSQL(saveInfo)
End Sub
There is obviously something I am missing, though I am not sure it is missing from the code. I checked my database fields and set them to string/text fields just to see if I could get it working. At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements. I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since. I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.
I am rather lost on what else to try as this seems like it should work one way or another. Any ideas what to look at and/or try?? Hopefully I can be pointed in the right direction.
Thanks :)
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.
Try this instead:
(Edited)
saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
mediatorID = '" & MediatorIDTextBox.Text & "'"
Also be sure to handle the date correctly. I usually force formatting in yyyy/mmm/dd format.

If or case statement based on radio button click

I am trying to find a way to run some code based on the selection of a radio button. I have several radio buttons in a groupbox which will run different code based on there selection. Now, being a fairly new user to VB.NET, I am struggling to correctly code this.
Would I be better to use an IF statement or a SELECT CASE statement. I have tried using a flag set as a boolean to indicate if button1 is selected, set flag = true. That is as far as I have got. I am using CheckedChanged event to handle to event changes. I have included some code and would be grateful if someone could start me off. Many thanks.
Private Sub rdbBoxReturn_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbBoxReturn.CheckedChanged
'code goes here
flagBoxReturn = True
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
If flagBoxReturn = True Then
MessageBox.Show(CStr(flagBoxReturn))
Return
Else
DBConnection.connect()
sql = "SELECT MAX([Id]) from Request Boxes WHERE Customer = '" & cmbCustomer.Text & "' "
'MessageBox.Show(cmbCustomer.Text)
'sql = "INSERT INTO [Requests] ("")"
'Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'i'"
Dim cmd As New OleDb.OleDbCommand
Dim id As String
Dim requestor As String = "DEMO"
Dim intake As String = "I"
Dim status As String = "O"
'cmd.Parameters.AddWithValue("#p1", cmbCustomer.Text)
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
'lvSelectRequestItems.Items.Clear()
While dr.Read()
id = CStr(CInt(dr.Item(0).ToString))
id = String.Format("{0:D6}", (Convert.ToInt32(id) + 1))
'id = CStr(CDbl(id) + 1)
End While
MessageBox.Show(CStr(id))
dr.Close()
sql = "INSERT INTO [Request Boxes] ([Request no], Customer, Dept, [Type], [Service level], [Date-time received], [Received by], [Date-time due], Quantity, [Cust requestor], Status ) " &
"VALUES ('" & id & "', '" & cmbCustomer.Text.ToUpper & "', '" & cmbDept.Text & "', '" & intake.ToString & "', '" & rbServiceLevel.ToString & "', '" & dtpDateReceived.Value & "', '" & requestor.ToString & "', '" & dtpDateDue.Value & "', '" & txtBoxQuantity.Text & "', '" & requestor.ToString & "', '" & status & "')"
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
oledbCnn.Close()
flagBoxReturn = False
MessageBox.Show("Your record number: " & id & " Was entered successfully")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
How about something like this...
Public Enum SaveOption As Int32
DoNothing = 0
DoSomething = 1 ' Obviously rename this to something that makes sense in your situation.
End Enum
Public Function GetSaveOption() As SaveOption
Dim result As SaveOption = SaveOption.DoNothing
If rdbBoxReturn.Checked Then
result = DoSomething
End If
' Add as many if statements her to cover all your radio buttons.
Return result
End Function
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Select Case GetSaveOption
Case SaveOption.DoNothing
Exit Sub
Case SaveOption.DoSomething
' Your save code here
End Select
End Sub
This method makes your code more readable by converting UI element states into program states.
Switch statement is better if the number of comparisons is small
if you had a radio button list control, that would be much better as in that case
switch statement can be passed the index variable (SelectedIndex property of the radio
button list) but that control is available in web forms, or can be available in win forms
if you find some free user/custom control etc.
so in your case, better to use if else statements

UPDATE statement failing when attempting to update access database - VB.Net

I am trying to create a simple ticketing software for myself with a VB.Net front end and an Access 2003 back end. I have with allowing new rows to be added, but when I try to code the Update row button, it is giving me the error that says Microsoft JET Database Engine - Syntax error in UPDATE statement. I cannot find what the problem is.
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim ConnectString As String = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\aaron-pister\Desktop\New Role Notes\Issue Tracker Express\Issue Tracker Express\Issue Tracker.mdb")
Dim con As New OleDbConnection(ConnectString)
con.Open()
Dim Green42 As String = "UPDATE Issues Basic Details SET [Company Name] = '" & txtClientName.Text & "', [Status] = '" & cbStatus.Text & "', [Company Contact] = '" & txtClientContact.Text & "', [Description] = '" & txtDesc.Text & "', [Notes] = '" & txtRes.Text & "' WHERE [TicketNum] = '" & txtTicket.Text & "'"
'con.Open()
If txtClientName.Text <> "" Then
Try
'MyCom.CommandText = "UPDATE [Issues Basic Details] SET Company Name = '" & txtClientName.Text & "', Status = '" & cbStatus.Text & "', Company Contact = '" & txtClientContact.Text & "', Description = '" & txtDesc.Text & "', Notes = '" & txtRes.Text & "' WHERE TicketNum = '" & txtTicket.Text & "')"
da = New OleDbDataAdapter(Green42.ToString, ConnectString)
da.Fill(dt)
da.Update(EsInfo1, "Issues Basic Details")
MsgBox("Your record has been updated successfully.", MsgBoxStyle.DefaultButton1, "New Ticket Submitted")
Catch ex As Exception
MsgBox(ex.Source & "-" & ex.Message)
con.Close()
Exit Sub
End Try
Else
MsgBox("You must have an entry in the Client Name, Client Contact and Status fields. It is recommended to also have a value in the Description field.", MsgBoxStyle.OkOnly, "Issue Tracker Express")
btnNewIncident_Click(sender, e)
Exit Sub
End If
End Sub
Your table name has to be bracketed too:
Dim Green42 As String = "UPDATE [Issues Basic Details] SET [Company Name]..."
Also, use parameters instead of putting the values into the string. It avoids SQL Injection.
This:
UPDATE Issues Basic Details SET ...
Is not valid SQL. You need to help it by qualifying your table name:
UPDATE [Issues Basic Details] SET ...
A few other suggestions:
Use prepared statements (parameterize your SQL to avoid SQL injection attacks)
Don't define this type of behavior in a click event handler -- have a helper class to do this work so it can be re-used and isn't coupled directly to the UI.
Use Using statements. Your OleDbConnection class implements IDisposable. You aren't properly disposing this connection.
While it's hard to read your code at the moment, it does look like you are trying to do an "AdHoc" query, which can cause a lot of problems.
I'd recommend first changing your statement to a parameterized query to help diagnose issues too.