I need to verify the operations done in an account at a particular period of time by asking the user to enter account number and the date range, but each time I run it I have the error "type mismatch"
Here is the code:
Private Sub cmdSearch_Click()
Call search
End Sub
Sub search()
Dim strCriteria, strCount, task As String
Me.Refresh
If IsNull(Me.compte_hist) Or IsNull(Me.date_deb) Or IsNull(Me.date_fin) Then
MsgBox "s'il vous plaƮt assurez-vous que tous les champs sont remplis", vbInformation, "Date Range Required"
Me.compte_hist.SetFocus
Else
strCriteria = "([Date_operation]>= #" & Me.date_deb & "# And [Date_operation] <= #" & Me.date_fin & "#)"
strCount = "[Compte]=#" & Me.compte_hist & "#"
task = "select * from Operations where Operations (" & strCriteria & ")" And " (" & strCount & ") order by [Date_operation]"
DoCmd.ApplyFilter task
End If
End Sub
Try this:
strCriteria = "([Date_operation]>= #" & Format(Me.date_deb, "mm\/dd\/yyyy") & "# And [Date_operation] <= #" & Format(Me.date_fin, "mm\/dd\/yyyy") & "#)"
strCount = "[Compte]=" & Me.compte_hist
task = "select * from Operations where (" & strCriteria & ") And (" & strCount & ") order by [Date_operation]"
Me.RecordSource = task
Also you can apply filter only:
strCriteria = "([Date_operation]>= #" & Format(Me.date_deb, "mm\/dd\/yyyy") & "# And [Date_operation] <= #" & Format(Me.date_fin, "mm\/dd\/yyyy") & "#)"
strCount = "[Compte]=" & Me.compte_hist
task = "(" & strCriteria & ") And (" & strCount & ")"
Me.Filter = task
Me.FilterOn = True
If account number is not numeric, use quotes:
strCount = "[Compte]='" & Me.compte_hist & "'"
Related
I have a query that that connects to several remote machines to union data into a single table. It works fine when all the machines are connected but occasionally any given machine may be turned off (which results in error), I'd like my query to ignore any connections that are unavailable and continue with the rest of the query. Is there any way to do this?
I'm using linked tables with an OBDC conncetion (driver: MySql ODBC 5.3 Ansi Driver)
Here is my query:
SELECT "HX32" AS workcenter, "HX32." & [HX32].[dataid] AS tbldataid, HX32.dataid AS dataid, HX32.TS, DMin("[TS]","[HX32]","[TS] > #" & [TS] & "#") AS EndTS, DateDiff("s",[TS],EndTS) AS durationsec, Format(Int([durationsec]/86400)) & " " & Format([durationsec]/86400,"hh:nn:ss") AS duration, Format(TS,"mm/dd/yyyy") AS [Day], Switch(incycle=0,'Down',incycle=1,'Running') AS Status
FROM HX32
WHERE (((HX32.TS)>Date()-3) AND ((HX32.incycle)=0))
UNION ALL
SELECT "VL65A" AS workcenter, "VL65A." & [VL65A].[dataid] AS tbldataid, VL65A.dataid AS dataid, VL65A.TS, DMin("[TS]","[VL65A]","[TS] > #" & [TS] & "#") AS EndTS, DateDiff("s",[TS],EndTS) AS durationsec, Format(Int([durationsec]/86400)) & " " & Format([durationsec]/86400,"hh:nn:ss") AS duration, Format(TS,"mm/dd/yyyy") AS [Day], Switch(incycle=0,'Down',incycle=1,'Running') AS Status
FROM VL65A
WHERE (((VL65A.TS)>Date()-3) AND ((VL65A.incycle)=0))
UNION ALL
SELECT "VL68B" AS workcenter, "VL68B." & [VL68B].[dataid] AS tbldataid, VL68B.dataid AS dataid, VL68B.TS, DMin("[TS]","[VL68B]","[TS] > #" & [TS] & "#") AS EndTS, DateDiff("s",[TS],EndTS) AS durationsec, Format(Int([durationsec]/86400)) & " " & Format([durationsec]/86400,"hh:nn:ss") AS duration, Format(TS,"mm/dd/yyyy") AS [Day], Switch(incycle=0,'Down',incycle=1,'Running') AS Status
FROM VL68B
WHERE (((VL68B.TS)>Date()-3) AND ((VL68B.incycle)=0))
;
I ended up using VBA to solve per #Erik's comments:
It loops through each connection checks it, if connection is good it modifies a query and runs.
Dim cnn As ADODB.Connection
Dim canConnect As Boolean
Set cnn = New ADODB.Connection
Dim conctns As Variant
Dim conctn As Variant
conctns = Array("HX32", "VL65A", "VL68B")
For Each conctn In conctns
On Error GoTo sub_error
cnn.Open conctn
If cnn.State = adStateOpen Then
canConnect = True
strSQL = "SELECT '" & conctn & "' AS workcenter, '" & conctn & ".' & [" & conctn & "].[dataid] AS tbldataid, " & conctn & ".dataid AS dataid, " & conctn & ".TS, DMin('[TS]','[" & conctn & "]','[TS] > #' & [TS] & '#') AS EndTS, DateDiff('s',[TS],EndTS) AS durationsec, Format(Int([durationsec]/86400)) & ' ' & Format([durationsec]/86400,'hh:nn:ss') AS duration, Format(TS,'mm/dd/yyyy') AS [Day], Switch(incycle=0,'Down',incycle=1,'Running') AS Status FROM " & conctn & " WHERE (((" & conctn & ".TS)>Date()-3) AND ((" & conctn & ".incycle)=0));"
CurrentDb.QueryDefs("unionall").SQL = strSQL
DoCmd.OpenQuery "appendall", acViewNormal, acEdit
DoCmd.OpenQuery "splithours", acViewNormal, acEdit
MsgBox conctn & " updated: " & canConnect
cnn.Close
End If
sub_error:
MsgBox conctn & ": " & Error$
Resume sub_error_exit
sub_error_exit:
Next conctn
I am facing a little issue now. My issue is that currently when i made edit to the current record in my subform and click on "update" it will overwrite my previous record which i do not want.
Instead, I would like to add my edited data record from the subform and insert it into the subform as a new record with the same PO number as the one that i am editing.
Below are my code:
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtID.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO mxd " & _
"(ID,Fabrication,Width,FinishedGoods,Colour, " & _
"LabDipCode,GrossWeight,NettWeight, " & _
"Lbs,Loss,Yds,Remarks,POType,ComboName,GroundColour)" & _
" VALUES(" & Me.txtID & ",'" & Me.txtFabrication & "','" & _
Me.txtWidth & "','" & Me.txtFinishedGood & "','" & _
Me.txtColour & "','" & Me.txtLabDipCode & "','" & _
Me.txtGrossweight & "','" & _ Me.txtNettweight & "','" & _
Me.txtLbs & "','" & Me.txtLoss & "','" & _ Me.txtYds & "','" & _
Me.txtRemarks & "','" & Me.cboPoType "','" & _
Me.txtGroundColour & "','" & Me.txtComboName & "')"
Else
'otherwise (Tag of txtID store the id of student to be modified)
CurrentDb.Execute "UPDATE mxd " & _
" SET ID = " & Me.txtID & _
", Fabrication = '" & Me.txtFabrication & "'" & _
", Width = '" & Me.txtWidth & "'" & _
", FinishedGoods = '" & Me.txtFinishedGood & "'" & _
", Colour = '" & Me.txtColour & "'" & _
", LabDipCode = '" & Me.txtLabDipCode & "'" & _
", GrossWeight = '" & Me.txtGrossweight & "'" & _
", NettWeight = '" & Me.txtNettweight & "'" & _
", LBS = '" & Me.txtLbs & "'" & _
", Loss = '" & Me.txtLoss & "'" & _
", Yds = '" & Me.txtYds & "'" & _
", Remarks = '" & Me.txtRemarks & "'" & _
", POType = '" & Me.cboPoType & "'" & _
", ComboName = '" & Me.txtComboName & "'" & _
", GroundColour = '" & Me.txtGroundColour & "'" & _
" WHERE ID = " & Me.txtID.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
FormMxdSub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtID = ""
Me.txtFabrication = ""
Me.txtWidth = ""
Me.txtFinishedGood = ""
Me.txtColour = ""
Me.txtLabDipCode = ""
Me.txtGrossweight = ""
Me.txtNettweight = ""
Me.txtLbs = ""
Me.txtLoss = ""
Me.txtYds = ""
Me.txtRemarks = ""
Me.cboPoType = ""
Me.txtKeywords = ""
Me.txtComboName = ""
Me.txtGroundColour = ""
'focus on ID text box
Me.txtID.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtID for reset new
Me.txtID.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.FormMxdSub.Form.Recordset.EOF And
Me.FormMxdSub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM mxd " & _
"where ID = " & Me.FormMxdSub.Form.Recordset.Fields("ID")
'refresh data in list
Me.FormMxdSub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there is exists data in list
If Not (Me.FormMxdSub.Form.Recordset.EOF And
Me.FormMxdSub.Form.Recordset.BOF) Then
'get data to text box control
With Me.FormMxdSub.Form.Recordset
Me.txtID = .Fields("ID")
Me.txtFabrication = .Fields("Fabrication")
Me.txtWidth = .Fields("Width")
Me.txtFinishedGood = .Fields("FinishedGoods")
Me.txtColour = .Fields("Colour")
Me.txtLabDipCode = .Fields("LabDipCode")
Me.txtGrossweight = .Fields("GrossWeight")
Me.txtNettweight = .Fields("NettWeight")
Me.txtLbs = .Fields("Lbs")
Me.txtLoss = .Fields("Loss")
Me.txtYds = .Fields("Yds")
Me.txtRemarks = .Fields("Remarks")
Me.cboPoType = .Fields("POType")
Me.txtComboName = .Fields("ComboName")
Me.txtGroundColour = .Fields("GroundColour")
'store id of student in Tag of txtID in case id is modified
Me.txtID.Tag = .Fields("ID")
'change caption of button add to update
'Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
You can use the RecordsetClone to create a dupe of the current record. Much faster and cleaner and no Tag is needed:
Private Sub btnCopy_Click()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
If Me.NewRecord = True Then Exit Sub
Set rstInsert = Me.RecordsetClone
Set rstSource = rstInsert.Clone
With rstSource
If .RecordCount > 0 Then
' Go to the current record.
.Bookmark = Me.Bookmark
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
ElseIf .Name = "SomeFieldToExclude" Then
' Leave field blank.
ElseIf .Name = "SomeOtherFieldToExclude" Then
' Leave field blank.
Else
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End With
Next
.Update
' Go to the new record and sync form.
.MoveLast
Me.Bookmark = .Bookmark
.Close
End With
End If
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub
Of course, if you place the button on the main form, replace in the code Me with a reference to the subform: Me!NameOfYourSubformControl.Form
I have the following function running on form load when the database opens. I know something is missing but I am not sure what exactly. The code runs fine until it opens a form so the user can select a printer. Then the form has it's own that it works through.
I put a break in and the code stops on the SelectPrinter sub so I guess I need that code to return to the function or can I write the code into the function?
This is the function:
Option Compare Database
Function PrintReports()
Dim ExeCount As Long
Dim ExdCount As Long
Dim ExiCount As Long
Dim ExnCount As Long
Dim ExpCount As Long
Dim Answer As Integer
DoCmd.SetWarnings (WarningsOff)
'Create Ex e Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date]))
AS Due_Date " & _
"INTO tbl_Ex_e " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex e','Ex eb','Ex ed','Ex em','Ex
emb','Ex mb','Ex mbe','Ex me')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex d Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_d " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Class 1','Ex d','Ex de','Ex dmb')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex i Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_i " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex i','Ex ia')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex n Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_n " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex n','Ex nA','Ex nR')))" & _
"ORDER BY tbl_AHAD.Maint_Item"
'Create Ex p Table
DoCmd.RunSQL "SELECT tbl_AHAD.*, IIf([Last_Insp_Date] Is
Null,Date(),DateAdd('yyyy',4,[Last_Insp_Date])) AS Due_Date " & _
"INTO tbl_Ex_p " & _
"FROM tbl_AHAD " & _
"WHERE (((IIf([Last_Insp_Date] Is Null,Date(),DateAdd('yyyy',4,
[Last_Insp_Date])))<=Date()) " & _
"AND ((tbl_AHAD.Device_Class) In ('Ex p'))) " & _
"ORDER BY tbl_AHAD.Maint_Item"
DoCmd.SetWarnings (WarningsOff)
'Open message box to ensure user wants to continue
ExeCount = DCount("ID", "tbl_Ex_e")
ExdCount = DCount("ID", "tbl_Ex_d")
ExiCount = DCount("ID", "tbl_Ex_i")
ExnCount = DCount("ID", "tbl_Ex_n")
ExpCount = DCount("ID", "tbl_Ex_p")
Answer = MsgBox("There are " & vbCrLf & vbCrLf & ExeCount & " Ex e Reports
" & vbCrLf & ExdCount & " Ex d Reports " & vbCrLf & _
ExiCount & " Ex i Reports" & vbCrLf & ExnCount & " Ex n Reports" &
vbCrLf & ExpCount & " Ex p Reports" & _
vbCrLf & vbCrLf & "Records to Print", vbOKCancel)
'If Ok then print all reports
If Answer = vbOK Then
DoCmd.OpenForm "SelectPrinter", , , , , acDialog
**'Stopping here**
Set Application.Printer = _
Application.Printers(cboDestination.ListIndex)
DoCmd.Close acForm, "SelectPrinter", acSaveYes
If ExpCount > 0 Then
DoCmd.OpenReport "rpt_Ex_p"
End If
' Switch back to original default printer
Set Application.Printer = Application.Printers(strDefaultPrinter)
Else
Exit Function
End If
'Update table with today's date
DoCmd.RunSQL "UPDATE tbl_AHAD INNER JOIN tbl_Ex_p ON tbl_AHAD.ID = tbl_Ex_p.ID " & _
"SET tbl_AHAD.Last_Insp_Date = Date() "
End Function
This is the sub that runs along with it's function after the DoCmd.OpenForm "SelectPrinter", , , , , acDialog
Private Sub Form_Load()
cboDestination = ""
m_GetPrinters cboDestination
cboDestination.SetFocus
cboDestination.ListIndex = 0
End Sub
Public Sub m_GetPrinters(ByRef objListOrCombo As Object)
Dim objPrinter As Printer
Dim intNbOfPrinters As Integer
intNbOfPrinters = Printers.Count - 1
For Each objPrinter In Printers
objListOrCombo.AddItem objPrinter.DeviceName
Next
End Sub
You specifically open the form in dialogue mode:
DoCmd.OpenForm "SelectPrinter", , , , , acDialog
Thus, your code will not stop, but it turns to the form opened and silently waits until that form is closed - then the code will proceed.
If you wish to open the form and have the function PrintReports() to continue without taking notice of the form, then don't use the acDialog setting.
I want to update serial.Issuedate getting from form but its giving syntax error.
Please help me how can I correct this error.
My code is below:
Private Sub Command30_Click()
Set serialrs = CurrentDb.OpenRecordset("serial")
Dim Idate As Date
Dim Itodo As String
Idate = Me.IssuedDate.Value
Itodo = Me.IssuedToDO.Value
Dim issueqry As String
issueqry = "UPDATE serial " _
& " set serial.IssueToDO = '" & Itodo & "'" _
& " serial.issuedate = (#" & Format(Idate, "mm\/dd\/yyyy") & "#)" _
& " WHERE (((serial.id) Between 1 And 10)) "
DoCmd.RunSQL issueqry
MsgBox ("Issued Done")
End Sub
When you update more than one field, you must include a comma between the field expressions like this ...
SET [field name] = "foo", [another field] = 17
^
here
So try your code like this ...
issueqry = "UPDATE serial " _
& " set serial.IssueToDO = '" & Itodo & "'," _
& " serial.issuedate = #" & Format(Idate, "mm/dd/yyyy") & "#" _
& " WHERE serial.id Between 1 And 10"
Also give yourself an opportunity to inspect the string the code built ...
Debug.Print issueqry
You can view the output from Debug.Print in the Immediate window. Ctrl+g will take you there.
When I click on save, I get the message:
You have an error in your SQL syntax;Check the manual that corresponds to your mySQL Server version for the right Syntax to use near 'idDrug=21' at line 21
Here is my code:
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim i As Integer
Dim xid As Integer
Dim xQTY(0) As Integer
Dim xQTY_ID(0) As Integer
Dim xCount As Integer
Dim xCounter_ID(0) As Integer
'Dim sqlstrx(5) As String
xid = 0
If lstitems.Items.Count > 0 Then
If Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO orders (CustID, Cust_Name, order_date) " & _
"VALUES (" & txtcustid.Text & ", " _
& "'" & txtcustname.Text & "', " _
& "'" & Format(dttoday.Value, "yyyy-MM-dd") & "')"
ExecuteSQLQuery(sqlSTR)
sqlSTR = "SELECT * FROM orders ORDER BY order_no DESC"
ExecuteSQLQuery(sqlSTR)
xid = sqlDT.Rows(0)("order_no")
For i = 0 To lstitems.Items.Count - 1
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, Unit_Cost, qty, totalcost) " & _
"VALUES (" & xid & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& "'" & lstitems.Items(i).SubItems(2).Text & "', " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(3).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
Next
Else
'delete first
For i = 0 To UBound(deleteID)
ExecuteSQLQuery("DELETE FROM Orders_detail WHERE order_no =" & txtorderno.Text & " AND idDrug =" & deleteID(i))
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity +" & Delete_QTY(i) & _
" WHERE idDrug =" & deleteID(i)
ExecuteSQLQuery(sqlSTR)
Next
For i = 0 To UBound(deleteID)
ReDim deleteID(i)
deleteID(i) = 0
Next
del = 0
'--
'If lstitems.Items.Count > 0 Then
For i = 0 To lstitems.Items.Count - 1
'MsgBox(stockID & " " & lstitems.Items(i).Text)
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " AND idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
If sqlDT.Rows.Count > 0 Then
ReDim Preserve xQTY(i), xQTY_ID(i)
xQTY(i) = sqlDT.Rows(0)("QTY")
'xQTY_ID(i) = sqlDT.Rows(0)("Item_ID")
End If
'MsgBox(sqlDT.Rows(0)("QTY"))
Next
For i = 0 To lstitems.Items.Count - 1
'MsgBox(xQTY_ID(i))
If lstitems.Items(i).Index <= (UBound(xQTY)) Then
If CDbl(lstitems.Items(i).SubItems(4).Text) < xQTY(i) Then
'MsgBox(xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text))
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE Order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockBalances SET ItemQuantity = ItemQuantity + " & (xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
ElseIf CDbl(lstitems.Items(i).SubItems(4).Text) > xQTY(i) Then
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE Stockbalances SET ItemQuantity = ItemQuantity - " & (CDbl(lstitems.Items(i).SubItems(4).Text) - xQTY(i)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
End If
End If
Next
' End If
'search for new item
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " ORDER BY Order_Dtl ASC"
ExecuteSQLQuery(sqlSTR)
xCount = sqlDT.Rows.Count
For i = 0 To sqlDT.Rows.Count - 1
ReDim Preserve xCounter_ID(i)
xCounter_ID(i) = sqlDT.Rows(i)("idDrug")
' xCount = i + 1
Next
'check
If lstitems.Items.Count > xCount Then
For i = 0 To lstitems.Items.Count - 1
If i > UBound(xCounter_ID) Then
'MsgBox(lstitems.Items(i).Text)
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, price, qty, totalcost) " & _
"VALUES (" & txtorderno.Text & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(0).Text & "', " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& lstitems.Items(i).SubItems(2).Text & ", " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(4).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
Next
End If
End If
Else
MsgBox("Can't save without details !!", MsgBoxStyle.Exclamation, xTitlename)
Exit Sub
End If
MsgBox("Record has been saved !!", MsgBoxStyle.Information, xTitlename)
sqlSTR = "SELECT distinct orders.order_no AS 'Order No.', Cust_Name as 'Customer Name', order_date AS 'Date', sum(totalcost) AS 'TOTAL DUE' FROM orders_detail " & _
"INNER JOIN orders ON orders_detail.order_no = orders.order_no " & _
"WHERE order_date ='" & Format(dttoday.Value, "yyyy-MM-dd") & "' GROUP BY orders.order_no, Cust_Name, order_date"
FillListView(ExecuteSQLQuery(sqlSTR), FrmORDERLIST.lstorder, 0)
Me.Close()
End Sub
It is impossible to fix all of your code and to be precise what is the exact cause of your error.
Suffice to say that you never should do a database application using that kind of string concatenation approach. Any of your text fields could cause the error because it contains single quotes or any of your date items could cause the error because it is not formatted how the database requires. (Same for decimals and other floating point values).
To solve this problems (and to avoid the dangerous Sql Injection scenarion) exists the parameterized queries approach.
So, just an example on what you need to do for every line of your sql commands
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, " & _
"Unit_Cost, qty, totalcost) VALUES (" & _
"#id, #iddrug, #dname,#unit, #qty, #total)"
Using cmd = new MySqlCommand(sqlStr, connection)
cmd.Parameters.AddWithValue("#id", xid)
cmd.Parameters.AddWithValue("#idrug", Convert.ToInt32(lstitems.Items(i).Text))
cmd.Parameters.AddWithValue("#dname", lstitems.Items(i).SubItems(1).Text)
cmd.Parameters.AddWithValue("#unit", lstitems.Items(i).SubItems(2).Text)
cmd.Parameters.AddWithValue("#qty", Convert.ToDecimal(lstitems.Items(i).SubItems(3).Text ))
cmd.Parameters.AddWithValue("#total", Convert.ToDecimal(lstitems.Items(i).SubItems(4).Text))
cmd.ExecuteNonQuery()
End Using
Notice how, in a parameterized query, you could specify the datatype of the value passed for the parameter using the Convert.ToXXXXX method. In this way the framework code could prepare the appropriate formatting of your values to be passed to the database engine.
Not to mention the now readable query text.