If or case statement based on radio button click - vb.net

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

Related

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

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

Why do I get a "data type conversion error" with ExecuteNonQuery()?

Why do I get an error converting varchar into float conversion when I run this code?
I can't figure it out, please help.
Imports System.Data.SqlClient
Public Class Form1
Dim selected As Double
Dim HourItem As Double
Dim OverTimeRate As Double
Dim connection As New SqlConnection("Data Source=DESKTOP-F55AVQ6\SQLEXPRESS;Initial Catalog=Db_Suncrest_Financial;Integrated Security=True")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Db_Suncrest_FinancialDataSet.Tb_Suncrest_Financial_Payroll' table. You can move, or remove it, as needed.
Me.Tb_Suncrest_Financial_PayrollTableAdapter.Fill(Me.Db_Suncrest_FinancialDataSet.Tb_Suncrest_Financial_Payroll)
End Sub
Private Sub Employee_PositionComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Employee_PositionComboBox.SelectedIndexChanged
Select Case Employee_PositionComboBox.SelectedItem
Case "Banker"
selected = 14.75
Case "Bank Teller"
selected = 10
Case "Loan Processor"
selected = 17.1
Case "Mortgage Consultant"
selected = 19.22
Case "Investment Representative"
selected = 19.31
Case "Credit Analyst"
selected = 19.88
Case "Investment Banker"
selected = 22.75
Case "Relationship Manager"
selected = 23.85
Case "Financial Adviser"
selected = 23.99
Case "Financial Analyst"
selected = 25.84
Case "Asset Manager"
selected = 26.86
Case "Under Writer"
selected = 27.56
Case "Internal Auditor"
selected = 28.79
Case "Investment Banking Analyst"
selected = 39.37
Case "Loan Officer"
selected = 43.18
End Select
Rate_Per_HourTextBox.Text = selected
End Sub
Private Sub Hours_WorkedComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Hours_WorkedComboBox.SelectedIndexChanged
Select Case Hours_WorkedComboBox.SelectedItem
Case "8"
HourItem = 8
Case "7"
HourItem = 7
Case "6"
HourItem = 6
Case "5"
HourItem = 5
Case "4"
HourItem = 4
End Select
End Sub
Private Sub OverTime_RateComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles OverTime_RateComboBox.SelectedIndexChanged
Select Case OverTime_RateComboBox.SelectedItem
Case "Normal Day"
OverTimeRate = 1.25
Case "Rest Day"
OverTimeRate = 1.69
Case "Special Non-Working Hoiday"
OverTimeRate = 1.69
Case "Special Non-Working Hoiday + Rest Day"
OverTimeRate = 1.95
Case "Regular Holliday"
OverTimeRate = 2.6
Case "Regular Holliday + Rest Day"
OverTimeRate = 3.38
End Select
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Basic_PayTextBox.Text = HourItem * selected * 30
OverTime_PayTextBox.Text = OverTimeRate * selected * OverTime_HoursTextBox.Text
Gross_SalaryTextBox.Text = OverTime_PayTextBox.Text + Basic_PayTextBox.Text
Total_Salary_W_TaxTextBox.Text = Gross_SalaryTextBox.Text * (0.0034 + 0.0363 + 0.01375)
Date_TimeTextBox.Text = Format(Now, "General Date")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
connection.Open()
Dim command As New SqlCommand("Insert into Tb_Suncrest_Financial_Payroll(Employee_Id_No, Employee_Name, Employee_Position, Residence, Date_Time, Hours_Worked, Rate_Per_Hour,
Basic_Pay, OverTime_Hours, OverTime_Rate, OverTime_Pay, Gross_Salary, SSS, Pagibig, Philhealth, Total_Salary_W_Tax)
Values(
'" & Employee_Id_NoTextBox.Text & "', '" & Employee_NameTextBox.Text & "', '" & Employee_PositionComboBox.Text & "', '" & ResidenceTextBox.Text & "', '" & Date_TimeTextBox.Text & "',
'" & Hours_WorkedComboBox.Text & "', '" & Rate_Per_HourTextBox.Text & "', '" & Basic_PayTextBox.Text & "', '" & OverTime_HoursTextBox.Text & "', '" & OverTime_RateComboBox.Text & "',
'" & OverTime_PayTextBox.Text & "', '" & Gross_SalaryTextBox.Text & "', '" & SSSTextBox.Text & "', '" & PagibigTextBox.Text & "', '" & PhilhealthTextBox.Text & "', '" & Total_Salary_W_TaxTextBox.Text & "')", connection)
command.Parameters.AddWithValue("#Employee_Id_No", SqlDbType.Int)
command.Parameters.AddWithValue("#Employee_Name", SqlDbType.VarChar)
command.Parameters.AddWithValue("#Employee_Position", SqlDbType.VarChar)
command.Parameters.AddWithValue("#Residence", SqlDbType.VarChar)
command.Parameters.AddWithValue("#Date_Time", SqlDbType.DateTime)
command.Parameters.AddWithValue("#Hours_Worked", SqlDbType.Int)
command.Parameters.AddWithValue("#Rate_Per_Hour", SqlDbType.Float)
command.Parameters.AddWithValue("#Basic_Pay", SqlDbType.Float)
command.Parameters.AddWithValue("#OverTime_Hours", SqlDbType.Float)
command.Parameters.AddWithValue("#OverTime_Rate", SqlDbType.Float)
command.Parameters.AddWithValue("#OverTime_Pay", SqlDbType.Float)
command.Parameters.AddWithValue("#Gross_Salary", SqlDbType.Float)
command.Parameters.AddWithValue("#SSS", SqlDbType.Float)
command.Parameters.AddWithValue("#Pagibig", SqlDbType.Float)
command.Parameters.AddWithValue("#Philhealth", SqlDbType.Float)
command.Parameters.AddWithValue("#Total_Salary_W_Tax", SqlDbType.Float)
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("Added")
Else
MessageBox.Show("Not Added")
End If
connection.Close()
End Sub
End Class
TL;DR; See this answer as to how to call SQL Server correctly.
Well, instead of using SQL parameters properly, you have just concatenated the values directly into the query. For example, although you have added a parameter:
command.Parameters.AddWithValue("#Employee_Id_No", SqlDbType.Int)
you are not actually using it:
'" & Employee_Id_NoTextBox.Text & "'
Instead you need to write your insert like this, no concatenation needed:
Values(#Employee_Id_No, #Employee_Name ...
See also this article by Dan Guzman about why not to use AddWithValue, especially for varchar columns.
You should use
Add("#Employee_Name", SqlDbType.VarChar, insert_column_length).Value = Employee_Id_NoTextBox.Text;
You should also not cache connection and command objects. Dispose them with using blocks.
EDIT
You also need to cast your Text values to the various types, for example CInt(Employee_Id_NoTextBox.Text)
Here is an example of the ideas presented by #Charlieface excellent answer.
A few points in addition.
It is very common for ID fields to be identity fields (auto-number) Check your database.
If this is the case then you would not include Employee_ID in the fields list, Values list of add anything to the parameters collection for that field. In your case this appears to be a payroll table so perhaps Employee_ID is a foreign key to an employees table elsewhere. In this case, the code is fine.
Users are apt to enter anything is a TextBox. I strongly suggest that you validate all the input for numbers and dates with .TryParse before attempting the insert.
Never present a message box while a connection is open. Connections are precious resources and should be opened directly before the .Execute... and closed as soon as possible with End Using.
There appears to be several calculated fields that do not need to be stored at all but storage is cheap and it will probably make other queries simpler.
Private ConStr As String = "Your connection string"
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim RetVal As Integer
Dim Sql = "Insert into Tb_Suncrest_Financial_Payroll(Employee_Id_No, Employee_Name, Employee_Position, Residence, Date_Time, Hours_Worked, Rate_Per_Hour,
Basic_Pay, OverTime_Hours, OverTime_Rate, OverTime_Pay, Gross_Salary, SSS,
Pagibig, Philhealth, Total_Salary_W_Tax)
Values(
#Employee_Id_No, #Employee_Name, #Employee_Position, #Residence, #Hours_Worked,#Rate_Per_Hour,
#Basic_PayTextBox, #OverTime_Hours, #OverTime_Rate, #Gross_Salary, #SSS,
#Pagibig, #Philhealth, #Total_Salary_W_Tax);"
Using connection As New SqlConnection(ConStr),
command As New SqlCommand(Sql, connection)
With command.Parameters
.Add("#Employee_Id_No", SqlDbType.Int).Value = CInt(Employee_Id_NoTextBox.Text)
.Add("#Employee_Name", SqlDbType.VarChar).Value = Employee_NameTextBox.Text
.Add("#Employee_Position", SqlDbType.VarChar).Value = Employee_Position.Text
.Add("#Residence", SqlDbType.VarChar).Value = ResidenceTextBox.Text
.Add("#Date_Time", SqlDbType.DateTime).Value = CDate(Date_TimeTextBox.Text)
.Add("#Hours_Worked", SqlDbType.Int).Value = CInt(Hours_WorkedComboBox.Text)
.Add("#Rate_Per_Hour", SqlDbType.Float).Value = CDbl(Rate_Per_HourTextBox.Text)
.Add("#Basic_Pay", SqlDbType.Float).Value = CDbl(Basic_PayTextBox.Text)
.Add("#OverTime_Hours", SqlDbType.Float).Value = CDbl(OverTime_HoursTextBox.Text)
.Add("#OverTime_Rate", SqlDbType.Float).Value = CDbl(OverTime_RateComboBox.Text)
.Add("#OverTime_Pay", SqlDbType.Float).Value = CDbl(OverTime_PayTextBox.Text)
.Add("#Gross_Salary", SqlDbType.Float).Value = CDbl(Gross_SalaryTextBox.Text)
.Add("#SSS", SqlDbType.Float).Value = CDbl(SSSTextBox.Text)
.Add("#Pagibig", SqlDbType.Float).Value = CDbl(PagibigTextBox.Text)
.Add("#Philhealth", SqlDbType.Float).Value = CDbl(PhilhealthTextBox.Text)
.Add("#Total_Salary_W_Tax", SqlDbType.Float).Value = CDbl(Total_Salary_W_TaxTextBox.Text)
End With
connection.Open()
RetVal = command.ExecuteNonQuery
End Using
If RetVal = 1 Then
MessageBox.Show("Added")
Else
MessageBox.Show("Not Added")
End If
End Sub

No value given for one or more required parameters (access)

I have 2 datatable with these fields
*dataordner
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
*datalemari
Archive Date/Time (datetimepicker, it's already data)
Storage Short Text (combobox)
Lemari Short Text (combobox)
BulanOrdner ShortText (combobox)
TahunOrdner Date/Time (datetimepicker)
and now I am very confused why i'm wrong
What I have tried:
I've done with my codes but always error with that error "no value given for one more...."
I call 2 table with if else in combobox(storage)
These are my code sequences, i think that's all true with selected item in combobox
note:
storage = combobox
Private Sub storage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles storage.SelectedIndexChanged
If storage.SelectedIndex = 1 Then
groupordner.Visible = True
grouplemari.Visible = False
Else
If storage.SelectedIndex = 2 Then
groupordner.Visible = False
grouplemari.Visible = True
End If
End If
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem = "Ordner" Then
str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
proses.ExecuteNonQuery(str)
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
End Sub
There might me some control's value that is null or Nothing, you can use Debugging with Breakpoints to check null values Or there might be Objects that are not initialized.
You can also try the code below :
Note : I will recommend you to use Parameterized Query instead
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
If storage.SelectedItem Is Nothing Then
MsgBox("Plese Select the item first", MsgBoxStyle.Exclamation)
Else
If conn.State <> ConnectionState.Open Then
conn.Open() '' Assuming conn is your OleDbConnection
End If
Dim cmd As OleDbCommand = conn.CreateCommand
Try
If storage.SelectedItem = "Ordner" Then
Str = "Update dataordner set Storage = " & storage.Text & ", BulanOrdner = " & bulanordner.Text & ", TahunOrdner = '" & tahunordner.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
Else
If storage.SelectedItem = "Lemari" Then
Str = "Update datalemari set Storage = " & storage.Text & ", Lemari = " & lemari.Text & ", BulanLemari = " & bulanlemari.Text & ", TahunLemari = '" & tahunlemari.Value & "' Where Archive = '" & tanggalarchive.Value & "'"
cmd.CommandText = Str
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Saved", MessageBoxButtons.OK)
Call bersih()
Call data_penjualan()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
Finally
conn.Close()
End Try
End If
End Sub

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.

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.