No value given for one or more required parameter vb.net error - vb.net-2010

Im making a hotel billing system and I want to create a button for update a record in MS access database.
here is my code:
Dim cmd As New OleDbCommand("Update CheckInList set TransactionID='" & CombotransID.Text & "',FirstName='" & guesttextbox1.Text & "', MiddleName='" & guesttextbox2.Text & "',LastName='" & guesttextbox1.Text & "',RoomNumber='" & RoomTextBox1.Text & "',Numberofdays='" & txtDaysNumber.Text & "', Noofchildren='" & Noofadultstxtbox1.Text & "',NoofAdults='" & noofchildrentextbox2.Text & "',CheckinDate='" & TxtCheckInDate.Text & "',CheckoutDatee='" & dtCheckOutDate.Text & "', SubTotal='" & TxtSubTotal.Text & "',AmnitiesAddonns='" & Txtamnities.Text & "', TotalBalance='" & TxtTotal.Text & "' where TransactionID=" & CombotransID.Text & "", conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Record Update Successfully")
After that I run the program and got the error message "No value given for one or more required parameter" and I don't know how to fix on it.

Related

How to avoid error 'Index was out of range. Must be non-negative and less than the size of the collection' which show on second time Data saved

I'm working on a vb.net project, which connected with sql 2008 server. Where I need to saved data from datagridview. It's work well for first time. After saved one data I just clear the datagridview and input new data on that datagridview. But in this time when I start the process for saving new data from datagridview to sql it show the error:
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
If con.State = 1 Then con.Close()
con.Open()
Using Debit_Product_ListCmd_CHK As New SqlClient.SqlCommand("select *from Debit_Product_List where DEBIT_NOTE_No='" & Trim(UCase(ProductCart.Rows(C).Cells(7).Value)) & "' and DEBIT_NOTE_DATE='" & Trim(UCase(ProductCart.Rows(C).Cells(8).Value)) & "' and ShopGSTNO='" & _
Trim(UCase(ProductCart.Rows(C).Cells(9).Value)) & "' and SupplierGSTNO='" & Trim(UCase(ProductCart.Rows(C).Cells(10).Value)) & "' and PRODUCT_CATEGORY='" & Trim(UCase(ProductCart.Rows(C).Cells(11).Value)) & "' and PRODUCT_SLNO='" & _
Trim(UCase(ProductCart.Rows(C).Cells(0).Value)) & "' and ProductDesc=#ProductDesc", con)
Debit_Product_ListCmd_CHK.Parameters.AddWithValue("#ProductDesc", Trim(UCase(ProductCart.Rows(C).Cells(1).Value)))
Dim readerRecordShowcmd As SqlDataReader = Debit_Product_ListCmd_CHK.ExecuteReader()
If readerRecordShowcmd.Read() Then
'Sale_Production_CUST_INVOICE_SLNO = ""
If rsdl.State = 1 Then rsdl.Close()
rsdl.Open("delete from Debit_Product_List where DEBIT_NOTE_No='" & Trim(UCase(ProductCart.Rows(C).Cells(7).Value)) & "' and DEBIT_NOTE_DATE='" & Trim(UCase(ProductCart.Rows(C).Cells(8).Value)) & "' and ShopGSTNO='" & _
Trim(UCase(ProductCart.Rows(C).Cells(9).Value)) & "' and SupplierGSTNO='" & Trim(UCase(ProductCart.Rows(C).Cells(10).Value)) & "' and PRODUCT_CATEGORY='" & Trim(UCase(ProductCart.Rows(C).Cells(11).Value)) & "' and PRODUCT_SLNO='" & _
Trim(UCase(ProductCart.Rows(C).Cells(0).Value)) & "'", conn)
If rsdl.State = 1 Then rsdl.Close()
rsdl.Open("delete from Debit_Product_TOTAL where DEBIT_NOTE_No='" & Trim(UCase(ProductCart.Rows(C).Cells(7).Value)) & "' and DEBIT_NOTE_DATE='" & Trim(UCase(ProductCart.Rows(C).Cells(8).Value)) & "' and ShopGSTNO='" & _
Trim(UCase(ProductCart.Rows(C).Cells(9).Value)) & "' and SupplierGSTNO='" & Trim(UCase(ProductCart.Rows(C).Cells(10).Value)) & "' and PRODUCT_CATEGORY='" & Trim(UCase(ProductCart.Rows(C).Cells(11).Value)) & "'", conn)
End If
End Using
con.Close()
I expect it will work as well as first data saved, but it show the error.

Missing comma error error inserting sql through access 2010 vba

Having the weirdest problem ever. I do have an sql insert statement, that properly works in sql. When i put that sql into vba it works very good from my pc. However, it does not work and shows sql error: missing comma. Where can be the problem??? I use Access 2010 plus, others use same Access version and having same ODB connections (DSN servers) . Some code example:
sql = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST= ODB)(PORT=1520))" & _
"(CONNECT_DATA=(SERVICE_NAME=ABTL))); uid=IN; pwd=XXX;"
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Set cmd = New ADODB.Command
con.Open sql
Set db = CurrentDb()
Set rst = db.OpenRecordset(strSQL)
Do While Not rst.EOF
insetSQL = con.Execute(" INSERT INTO STOCK (PNM_AUTO_KEY, PN, DESCRIPTION, HISTORICAL_FLAG, qty_oh, qty_adj, qty_available, CTRL_NUMBER, CTRL_ID, receiver_number, rec_date, serial_number,pcc_auto_key, cnc_auto_key, loc_auto_key, whs_auto_key, unit_cost, adj_cost, stc_auto_key, visible_mkt, remarks, ifc_auto_key, exp_date, unit_price, tagged_by, tag_date, owner, PART_CERT_NUMBER,ORIGINAL_PO_NUMBER, SHELF_LIFE, CTS_AUTO_KEY, MFG_LOT_NUM, AIRWAY_BILL )" & _
" VALUES ( " & rst![minimumas] & ", '" & rst![pn] & "', '" & "FROM_SCRIPT" & "', '" & "F" & "'," & rst![qty_oh] & "," & rst![qty_oh] & "," & rst![qty_oh] & "," & "G_STM_CTRL_NUMBER.nextval" & "," & "1" & ", '" & rst![receiver_number] & "', " & " TO_DATE('" & rst![rec_date] & "','YYYY-MM-DD'), '" & rst![serial_number] & "'," & rst![pcc_auto_key] & "," & rst![cnc_auto_key] & "," & rst![loc_auto_key] & "," & rst![whs_auto_key] & "," & rst![unit_cost] & "," & rst![unit_cost] & "," & "1" & ",'" & "T" & "', '" & rst![remarks] & "'," & _
"1" & ", " & " TO_DATE('" & rst![exp_date] & "','YYYY-MM-DD'), " & "0" & ",'" & rst![TAGGED_BY] & "', " & " TO_DATE('" & rst![tag_date] & "','YYYY-MM-DD'), '" & "" & "', '" & rst![PART_CERT_NUMBER] & "', '" & rst![ORIGINAL_PO_NUMBER] & "', '" & rst![SHELF_LIFE] & "', " & rst![CERT_SOURCE] & ", '" & rst![MFG_LOT_NUM] & "', '" & rst![AIRWAY_BILL] & "'" & " )")
Loop
It might be that one of the rescordset fields that is a string data type, has a value that contains a comma but you have not treated it as string.
eg
VALUES ( " & rst![minimumas] & ",
For the above code to work minimumas CANNOT contain any commas.
Are you certain that all the string fields int he recordset have been appended to the SQL string with a ' around them.
We need to see the sql string is created which then causes the error. Please provide this as requested.
=========================================================
PART 2 Viewing the SQL causing the error
replace
insetSQL = con.Execute(
with
on error resume next
strMySQl = the string currently used in the execute statement
insetSQL = con.Execute(strMySQl)
if err.number <> 0 then
stop
debug.print err.number, err.description
debug.print strMySQl
end if
then post the sql string that is printed in the immediate window to this site.
I would also suggest that you compare the SQL string generated on your machine with the other machines - just in case something weird is happening.

Edit/Update datagridview VB form

When I try to edit and update the data in datagriview it comes up with an error message saying Operator '&' is not defined for type 'TextBox' and string "".
please help. Thanks
Here is my code
Private Sub btnaddrecord_Click(sender As Object, e As EventArgs) Handles btnaddrecord.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.IdentificationNotest.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO vehicledefects(Codenumber, vehiclereg, datereported, defects1, repaired1, defects2, repaired2, defects3, repaired3, datefixed) " & _
" VALUES(" & Me.IdentificationNotest.Text & ",'" & Me.vehiclereg.Text & "','" & Me.datereported.Text & "','" & Me.defects1.Text & "','" & Me.repaired1.Text & "','" & _
Me.defects2.Text & "','" & Me.repaired2.Text & "','" & _
Me.defects3.Text & "','" & Me.repaired3.Text & "','" & _
Me.datefixed.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE vehicledefects" & _
" SET Codenumber =" & Me.IdentificationNotest.Text & _
", vehiclereg ='" & Me.vehiclereg.Text & "'" & _
", datereported ='" & Me.datereported.Text & "'" & _
", defects1 ='" & Me.defects1.Text & "'" & _
", repaired1 ='" & Me.repaired1.Text & "'" & _
", defects2 ='" & Me.defects2.Text & "'" & _
", repaired2='" & Me.repaired2.Text & "'" & _
", defects3='" & Me.defects3.Text & "'" & _
", repaired3='" & Me.repaired3.Text & "'" & _
", datefixed='" & Me.datefixed.Text & "'" & _
" WHERE Codenumber =" & Me.IdentificationNotest.Tag
cmd.ExecuteNonQuery()
End If
refreshdata()
Me.btnclear.PerformClick()
cnn.Close()
datefixed.Text = ""
IdentificationNotest.Text = ""
End Sub
In the future, you should also post the line number the error is being thrown on.
The error is telling you that you're doing something like:
dim myString as String = myTextBox & " some more text"
in this case, you would need to do:
dim myString as String = myTextBox.Text & " some more text"
In the code you posted, I wasn't able to find an instance of this - so perhaps its somewhere else in the code. Though, the code was hard to read so I may have missed it.
You may also be aware that this code is susceptible to SQL Injection attacks

Stoping Macro if Connection is Lost

I have a series of codes that run when designated, the first is a connection check. If it is successful then it allows the code to continue, if not it stops it altogether. I am worried however about what happens when the connection is lost after this process. There is data on a local table that is uploaded to our SQL server during this process, if the connection terminates mid download it looks like sometimes the data is still transferred but not if it happens right away.
The second part of the code, deletes all the local tables contents which contain employee information, then downloads the new data so if there were any updates the most recent information is provided.
I am trying to figure out if there is a method or code that can be implemented to tell the query to stop running as soon as connection is lost, or if there is a way to undo it if it happens.
Or would it be a good idea to combine the connection code with the upload and delete codes so it runs every time before it initiates a process?
The connection code that runs at the beginning is:
Public Function StartUp()
Dim cnn As ADODB.Connection
Dim localrst As New ADODB.Recordset
Dim remoterst As New ADODB.Recordset
On Error Resume Next
Set cnn = New ADODB.Connection
cnn.Open "Provider=PRO; Data Source=SOURCE; Initial Catalog=CAT;" _
& "User Id=ID; Password=PW;"
If cnn.State = adStateOpen Then
MsgBox ("You have an established connection with the L&TD SQL Server Database and the CDData table has been uploaded to the server.")
Else
MsgBox ("Cannot connect to SQL Server. Data will be stored locally to CDData Table until application is opened again with an established connection.")
End
End If
On Error GoTo 0
' MsgBox ("Please wait while the database is updating, this may take a moment.")
End Function
As you can see, I placed an END before the END IF so if there is no connection it just ends altogether.
The UPLOAD code is
Public Function Update()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim err As DAO.Error
' Const DestinationTableName = "AC_CDData"
Const ConnectionString = _
"ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=SERV;" & _
"Database=DB;" & _
"UID=ID;" & _
"PWD=PWD;"
Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
Set rs = CurrentDb.OpenRecordset("CDData", dbOpenTable)
qdf.Connect = ConnectionString
Do While Not rs.EOF
qdf.SQL = "INSERT INTO AC_CDData_1(EmployeeID, EmployeeName, Region, District, Function1, Gender, EEOC, Division, Center, MeetingReadinessLevel, ManagerReadinessLevel, EmployeeFeedback, DevelopmentForEmployee1, DevelopmentForEmployee2, DevelopmentForEmployee3, DevelopmentForEmployee4, DevelopmentForEmployee5, Justification, Notes, Changed, JobGroupCode, JobDesc, JobGroup) " & _
"Values (" & _
"'" & rs!EmployeeID & "', " & _
"'" & rs!EmployeeName & "', " & _
"'" & rs!Region & "', " & _
"'" & rs!District & "', " & _
"'" & rs!Function1 & "', " & _
"'" & rs!Gender & "', " & _
"'" & rs!EEOC & "', " & _
"'" & rs!Division & "', " & _
"'" & rs!Center & "', " & _
"'" & rs!ManagerReadinessLevel & "', " & _
"'" & rs!MeetingReadinessLevel & "', " & _
"'" & rs!EmployeeFeedback & "', " & _
"'" & rs!DevelopmentForEmployee1 & "', " & _
"'" & rs!DevelopmentForEmployee2 & "', " & _
"'" & rs!DevelopmentForEmployee3 & "', " & _
"'" & rs!DevelopmentForEmployee4 & "', " & _
"'" & rs!DevelopmentForEmployee5 & "', " & _
"'" & rs!Justification & "', " & _
"'" & rs!Notes & "', " & _
"'" & rs!Changed & "', " & _
"'" & rs!JobGroupCode & "', " & _
"'" & rs!JobDesc & "', " & _
"'" & rs!JobGroup & "')"
qdf.ReturnsRecords = False
On Error GoTo Update_qdfError
qdf.Execute dbFailOnError
On Error GoTo 0
rs.MoveNext
Loop
rs.Close
Set qdf = Nothing
Set cdb = Nothing
Set rs = Nothing
Exit Function
Update_qdfError:
For Each err In DAO.Errors
MsgBox err.Description, vbCritical, "Error " & err.Number
Next
End Function
So is there a way I can modify the Connection code and add it to the update code (minus the message boxes) so if the connection cuts off it will terminate the code?
Did you try out transactions? Wrapping your insert script inside a transaction will not change the database until you've explicitly committed the transaction. If the data connection is lost during the inserts, the commit will never be called, and the SQL Server data won't be changed.
See http://msdn.microsoft.com/en-us/library/office/ff196400%28v=office.15%29.aspx

Save when new record and update when edit on data occurs

I have my code for save button and update button but is there a way I can combine the two
commands in one button?
For example When I click 'SAVE/UPDATE Button' it will save on the database if it is a new record and it will rather update if the system found that there is already record on the database and save the edited data's
CODE FOR SAVE BUTTON
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Try
Dim myCommand As New SqlCommand
sqlconn.Open()
myCommand = New SqlCommand("INSERT INTO tblOfficeEquipmentProfile(OE_Category,OE_SubCategory,OE_ID,OE_Name,OE_User,OE_Brand,OE_Model,OE_Specs,OE_SerialNo,OE_PropertyNo,OE_MacAddress,OE_Static_IP,OE_Vendor,OE_PurchaseDate,OE_WarrantyInclusiveYear,OE_WarrantyStatus,OE_Status,OE_Dept_Code,OE_Location_Code,OE_Remarks) VALUES('" & cmbCategory.Text & "','" & cmbSubCategory.Text & "','" & txtOEID.Text & "','" & txtName.Text & "','" & txtUser.Text & "','" & cmbBrand.Text & "','" & cmbModel.Text & "','" & txtSpecs.Text & "','" & txtSerialNo.Text & "','" & txtPropertyNo.Text & "','" & txtMacAddress.Text & "','" & txtStaticIp.Text & "','" & txtVendor.Text & "','" & txtPurchaseDate.Text & "','" & txtWarrantyInclusiveYear.Text & "', '" & txtWarrantyStatus.Text & "','" & txtStatus.Text & "','" & cmbDeptCode.Text & "','" & cmbLocationCode.Text & "','" & txtRemarks.Text & "')", sqlconn)
myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Added")
sqlconn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
CODE FOR UPDATE BUTTON (NOTE: but still my update button has some error still trying to fix)
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim myCommand As New SqlCommand
Try
'update command
sqlconn.Open()
myCommand = New SqlCommand("UPDATE tblOfficeEquipmentProfile SET OE_Category = '" & cmbCategory.Text & "',OE_SubCategory = '" & cmbSubCategory.Text & "', OE_Name = '" & txtName.Text & "', OE_User = '" & txtUser.Text & "', OE_Brand = '" & cmbBrand.Text & "', OE_Model = '" & cmbModel.Text & "', OE_Specs = '" & txtSpecs.Text & "', OE_SerialNo = '" & txtSerialNo.Text & "', OE_PropertyNo = '" & txtPropertyNo.Text & "', OE_MacAddress = '" & txtMacAddress.Text & "', OE_Static_IP = '" & txtStaticIp.Text & "', OE_Vendor = '" & txtVendor.Text & "', OE_PurchaseDate = '" & txtPurchaseDate.Text & "', OE_WarrantyInclusiveYear = '" & txtWarrantyInclusiveYear.Text & "', OE_WarrantyStatus = '" & txtWarrantyStatus.Text & "', OE_Status = '" & txtStatus.Text & "', OE_Dept_Code = '" & cmbDeptCode.Text & "', OE_Location_Code = '" & cmbLocationCode.Text & "', OE_Remarks ='" & txtRemarks.Text & "' WHERE OE_ID ='" & txtOEID.Text & "'", sqlconn)
Dim iCnt As Integer = myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Updated " & iCnt & " Records")
Catch ex As Exception
MsgBox(ex.Message)
End Try
You could create an enum that contains the state:
Enum DataState
Editing
Adding
None
End Enum
Then set a class-level variable:
private mDataState as DataState
Then set this according to whether you are adding or editing a record, then in the Save_Click subroutine, use an If-Then.
Write a stored procedure that checks to see if the record exists. If it does, update it. Otherwise, insert it.
Call this stored procedure from your vb.net code. Also, change your .net code so that it sends query parameters to your stored procedure.
Yours is a perennial favorite question here on SO: how to update an existing row or else insert it? And the answers are perennially wrong.
The standard SQL to do this does not have an if statement. The standard way is to insert the row subject to the constraint that it does not exist, and then update it:
insert into T values (...)
where not exists (
select 1 from T as t
where T.key = t.key
)
optionally check the rowcount and only update if it's 0
update T set ...
where T.key = value
If you don't check the rowcount from insert, the update is redundant.
It's better to put all that in a stored procedure but, even if you don't, you should be able to put both statements in one prepared statement, and attach that to one button in your GUI.