looping with SqlDataAdapter vb.net - vb.net

I'm trying to loop according to the count of the gridview but it's giving me timeout at the second iteration.
Here's my code
Try
For i = 0 To Charges_GridView.Rows.Count - 2
'check unit price
'here is the error at the second iteration
Dim quantity As String = "SELECT QUANTITY FROM [dbo].[SERVICEITEMCHARGES] WHERE SERVICEITEMFID ='" & txt_FID.Text & "' AND FEESID = " & Charges_GridView.Rows(i).Cells(0).Value & " AND CURRENCY = '" & Charges_GridView.Rows(i).Cells(2).Value & "'"
Dim quantity_Adap As New SqlClient.SqlDataAdapter(quantity, conn)
Dim quantity_dt As New DataTable
quantity_Adap.Fill(quantity_dt)
If quantity_dt(0)(0) = 0 Then
'Update ServiceItemCharges
cmd.CommandText = "Update [dbo].[SERVICEITEMCHARGES] SET [AMOUNT] = " & Math.Ceiling(Charges_GridView.Rows(i).Cells(1).Value * 100) / 100 & ", UNIT_PRICE = 0 WHERE SERVICEITEMFID ='" & txt_FID.Text & "' AND FEESID = " & Charges_GridView.Rows(i).Cells(0).Value & " AND CURRENCY = '" & Charges_GridView.Rows(i).Cells(2).Value & "'"
cmd.Connection = connection
cmd.ExecuteNonQuery()
Else
'Update ServiceItemCharges
cmd.CommandText = "Update [dbo].[SERVICEITEMCHARGES] SET [AMOUNT] = " & Math.Ceiling(Charges_GridView.Rows(i).Cells(1).Value * 100) / 100 & ", UNIT_PRICE = " & (Math.Ceiling(Charges_GridView.Rows(i).Cells(1).Value * 100) / 100) / quantity_dt(0)(0) & " WHERE SERVICEITEMFID ='" & txt_FID.Text & "' AND FEESID = " & Charges_GridView.Rows(i).Cells(0).Value & " AND CURRENCY = '" & Charges_GridView.Rows(i).Cells(2).Value & "'"
cmd.Connection = connection
cmd.ExecuteNonQuery()
End If
Next
thanks for your help

Related

How to fix update code using short text as data type

Hello I just want to ask about my code. Why its showing error if I change the data type of ID_NO in short text? Btw database that I'm using is MS ACCESS
Dim i As Integer
i = dgMembers.CurrentRow.Index
currentid = dgMembers.Item(1, i).Value.ToString()
ds = New DataSet
adapter = New OleDbDataAdapter("update [FASA_MembersAccount] set ID_No = '" & txtMemberIDNo.Text & "',[FirstName] = '" & txtMemberFirstName.Text & "',[LastName] ='" & txtMemberLastName.Text & "',[Mobile_No] = '" & txtMemberMobileNo.Text & "',[Gender] = '" & cbMemberGender.Text & "',[Birthday] = '" & dtpMember.Text & "',[Password] = '" & txtMemberPassword.Text & "',[Address] = '" & txtMemberAddress.Text & "' where ID_No = " & currentid, conn)
adapter.Fill(ds, "FASA_MembersAccount")
Can somebody help me?
Here's an example of how to get your SQL code so you can run it in your database to check for syntax errors. Does this help?
Dim i As Integer
Dim strSQL as string
i = dgMembers.CurrentRow.Index
currentid = dgMembers.Item(1, i).Value.ToString()
ds = New DataSet
strSQL = "update [FASA_MembersAccount] set ID_No = '" & txtMemberIDNo.Text & "',[FirstName] = '" & txtMemberFirstName.Text & "',[LastName] ='" & txtMemberLastName.Text & "',[Mobile_No] = '" & txtMemberMobileNo.Text & "',[Gender] = '" & cbMemberGender.Text & "',[Birthday] = '" & dtpMember.Text & "',[Password] = '" & txtMemberPassword.Text & "',[Address] = '" & txtMemberAddress.Text & "' where ID_No = " & currentid
'--- Set your breakpoint here and use the immediate window to ?strSQL then copy/paste your command into ms-access
adapter = New OleDbDataAdapter(strSQL, conn)
adapter.Fill(ds, "FASA_MembersAccount")

problem converting a regular query to parametrized query

I came across this old piece of code that looks like this:
Dim sql As String = "exec wa_vterm_Insert_upd_Purchase_Card #merchant_id = '" & db.SqlSafe(sMerchantID) & "'" &
", #reference = '" & db.SqlSafe(reference) & "' " &
", #national_tax = " & nationalTax & " " &
", #customer_vat_number = '" & db.SqlSafe(customerVatNumber) & "' " &
", #discount_amount = " & discountAmount & " " &
", #duty_amount = " & dutyAmount & " " &
", #vat_invoice_number = '" & db.SqlSafe(vatInvoiceNumber) & "' " &
", #vat_tax_amount = " & vatTaxAmount & " " &
", #vat_tax_rate = " & vatTaxRate & " " &
", #destination_country_code = '" & db.SqlSafe(destCountryCode) & "' "
Trace.WriteLine(sql, LogLevel.Debug)
db.ExecuteNonQuery(sql)
I am converting this to parameterized query and I coded this:
Dim cmd As New SqlCommand("wa_vterm_Insert_upd_Purchase_Card", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#merchant_id", sqlDbType:=SqlDbType.VarChar).Value = sMerchantID
cmd.Parameters.Add("#reference", sqlDbType:=SqlDbType.VarChar).Value = reference
cmd.Parameters.Add("#national_tax", sqlDbType:=SqlDbType.VarChar).Value = nationalTax
cmd.Parameters.Add("#customer_vat_number", sqlDbType:=SqlDbType.VarChar).Value = customerVatNumber
cmd.Parameters.Add("#discount_amount", sqlDbType:=SqlDbType.VarChar).Value = discountAmount
cmd.Parameters.Add("#duty_amount", sqlDbType:=SqlDbType.VarChar).Value = dutyAmount
cmd.Parameters.Add("#vat_invoice_number", sqlDbType:=SqlDbType.VarChar).Value = vatInvoiceNumber
cmd.Parameters.Add(" #vat_tax_amount", sqlDbType:=SqlDbType.Decimal).Value = vatTaxAmount
cmd.Parameters.Add(" #vat_tax_rate", sqlDbType:=SqlDbType.Decimal).Value = vatTaxRate
cmd.Parameters.Add(" #destination_country_code", sqlDbType:=SqlDbType.VarChar).Value = destCountryCode
Try
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Trace.WriteLine(ex.Message & ex.Source, LogLevel.Debug)
Finally
cmd.Connection.Close()
End Try
however with the new piece of code I am getting this exception:
"Procedure or function 'wa_vterm_Insert_upd_Purchase_Card' expects parameter '#vat_tax_amount', which was not supplied."
I don't understand why??
As per the suggestion above the answer was a space in front of the #var_tax_amount

Fast and reliable way to insert into SQL table from vb.net Datagridview which has more than thousand rows

I would really appreciate if someone can help me to find a better solution than what I am doing now.
this is my vb.net insert command from the form which has dgvs with tables of 'dtOrders' and 'dtItems'. The issue I am facing now that sometimes all selected data doesn't insert into sql over internet dueto connection drop or slow connection. So what I want is send all data at once to sql and do the insert in sql stored procedure or something like that.
Sub Inserts() ' ScanPointLog, spSendToFactory
Dim CurrentDate = DateTime.Now.ToString("dd MMMM, yyyy hh:mm tt")
Try
'Insert Into ScanPointLog
MyCon.Open()
Query = "Declare #tId int set #tId=(select count(TripId) from ScanPointLog where BranchCode='" & BranchCodee & "' and ScanPoint='" & ScanPointName & "')+1
Insert into ScanPointLog(BranchCode, ScanPoint, TripId, DoneBy, DateTime, Driver, CarNo, ItemShouldBe, ActualTaken, MissedAny, MissedCount, TookExtra, ExtraCount, chkdSkipTrackItem, chkdSelectAllOrders,[Open])
Values('" & BranchCodee & "','" & ScanPointName & "',#tId,'" & UserIdd & "','" & CurrentDate & "','" & cmbDrivers.SelectedValue & "','" & txtCarNo.Text & "','" & TotalItemShouldBeForSelectedOrders & "','" & TotalItemTackenInTheTrip & "','" & IsThereAnyMissing & "','" & missingItems & "', '" & IsThereExtras & "','" & takingExtras & "',#skipTrckItem, #chckdAllOrdrs,1 )"
Command = New SqlCommand(Query, MyCon)
Command.Parameters.Add("#skipTrckItem", SqlDbType.Bit).Value = Convert.ToInt16(chbByPassTrackItem.Checked)
Command.Parameters.Add("#chckdAllOrdrs", SqlDbType.Bit).Value = Convert.ToInt16(chbSelectAllOrders.Checked)
Command.ExecuteNonQuery()
MyCon.Close()
'to get the saving tripid which was automatically took from above inser query
MyCon.Open()
Query = "Declare #tId int set #tId=(select count(TripId) from ScanPointLog where BranchCode='" & BranchCodee & "' and ScanPoint='" & ScanPointName & "')
select #tId as Result"
Command = New SqlCommand(Query, MyCon)
dtreaderTripIdafterSave = Command.ExecuteReader
While dtreaderTripIdafterSave.Read
ThisTripID = dtreaderTripIdafterSave.Item(0)
End While
lblTripID.Text = ThisTripID
MyCon.Close()
'Insert Orders into table spSendToFactory
MyCon.Open()
For Each row As DataRow In dtOrders.Rows
If row("Checked") = True Then
Dim TrackItem As Integer
If row("TrackItem") = "Yes" Then
TrackItem = 1
Else
TrackItem = 0
End If
Query = "If not Exists (Select * from spSendToFactory where OrderNo = #nOrderNo and IsItem=0 and BranchCode=#nBranchcode )
begin
Insert into spSendToFactory(OrderNo, DateTime, IsItem, BranchCode, TrackItem,CameFrom_Page,CameFrom_Table,CameFrom_TripID) Values(#nOrderNo,#nDtTm,0,#nBranchcode,#trkItem,'" & PreviouseScanPoint_Form & "','" & PreviouseScanPoint_Table & "','" & ThisTripID & "')
end;
Update spOrdered set TripId= '" & ThisTripID & "',Done= 1 where OrderNo = #nOrderNo AND IsItem=0;
Update Orders set OrderStatus= '" & ScanPointName & "' where OrderNo = #nOrderNo "
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", row("OrderNo").ToString)
Command.Parameters.AddWithValue("#nDtTm", CurrentDate)
Command.Parameters.AddWithValue("#nBranchcode", BranchCodee)
Command.Parameters.Add("#trkItem", SqlDbType.Bit).Value = TrackItem
Command.ExecuteNonQuery()
End If
Next
'Insert Items into table spSendToFactory
For Each iRow As DataRow In dtItems.Rows
If iRow("Checked") = True Then
Query = "If not Exists (Select * from spSendToFactory where OrderNo = #nOrderNo and IsItem=1 and ItemBarcode=#nItemBcode and BranchCode=#nBranchcode )
begin
Insert into spSendToFactory(OrderNo, DateTime, IsItem, ItemBarcode, BranchCode,CameFrom_Page,CameFrom_Table,CameFrom_TripID ) Values(#nOrderNo,#nDtTm,1,#nItemBcode,#nBranchcode,'" & PreviouseScanPoint_Form & "','" & PreviouseScanPoint_Table & "','" & ThisTripID & "')
end;
Update spOrdered set TripId= '" & ThisTripID & "', Done= 1 where OrderNo = #nOrderNo AND IsItem=1 AND ItemBarcode= #nItemBcode ;
Update OrderItem set ItemStatus= '" & ScanPointName & "' where OrderNo = #nOrderNo AND ItemBarcode= #nItemBcode "
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", iRow("OrderNo").ToString)
Command.Parameters.AddWithValue("#nDtTm", CurrentDate)
Command.Parameters.AddWithValue("#nItemBcode", iRow("ItemBarcode").ToString)
Command.Parameters.AddWithValue("#nBranchcode", BranchCodee)
Command.ExecuteNonQuery()
End If
Next
'Insert missing items into ScnPntMissItems
For Each mRow As DataRow In dtMissedItems.Rows
Query = "If not Exists
(Select * from ScnPntMissItems where
[BranchCode]='" & BranchCodee & "' and
[ScanPoint]= '" & ScanPointName & "' and
[TripId] = '" & ThisTripID & "' and
[OrderNo]= #nOrderNo and
[ItemBarcode] = #nItemBcode)
begin
Insert into ScnPntMissItems([BranchCode],[ScanPoint],[TripId],[DateTime],[OrderNo],[ItemName],[ItemBarcode]) Values('" & BranchCodee & "','" & ScanPointName & "','" & ThisTripID & "','" & CurrentDate & "',#nOrderNo,#nItemName,#nItemBcode)
end"
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", mRow("OrderNo").ToString)
Command.Parameters.AddWithValue("#nItemName", mRow("ItemName").ToString)
Command.Parameters.AddWithValue("#nItemBcode", mRow("ItemBarcode").ToString)
Command.ExecuteNonQuery()
Next
'Insert extra items into ScnPntExtraItems
For Each eRow As DataRow In dtExtarItems.Rows
Query = "If not Exists
(Select * from ScnPntExtraItems where
[BranchCode]='" & BranchCodee & "' and
[ScanPoint]= '" & ScanPointName & "' and
[TripId] = '" & ThisTripID & "' and
[OrderNo]= #nOrderNo and
[ItemBarcode] = #nItemBcode)
begin
Insert into ScnPntExtraItems([BranchCode],[ScanPoint],[TripId],[DateTime],[OrderNo],[ItemName],[ItemBarcode]) Values('" & BranchCodee & "','" & ScanPointName & "','" & ThisTripID & "','" & CurrentDate & "',#nOrderNo,#nItemName,#nItemBcode)
end;
Update spOrdered set TripId= '" & ThisTripID & "', Done= 1 where OrderNo = #nOrderNo AND IsItem=1 AND ItemBarcode= #nItemBcode ;
Update OrderItem set ItemStatus= '" & ScanPointName & "' where OrderNo = #nOrderNo AND ItemBarcode= #nItemBcode"
Command = New SqlCommand(Query, MyCon)
Command.Parameters.AddWithValue("#nOrderNo", eRow("OrderNo").ToString)
Command.Parameters.AddWithValue("#nItemName", eRow("ItemName").ToString)
Command.Parameters.AddWithValue("#nItemBcode", eRow("ItemBarcode").ToString)
Command.ExecuteNonQuery()
Next
Query = "Update ScanPointLog set [Close]=1 where BranchCode='" & BranchCodee & "' and ScanPoint='" & ScanPointName & "' and TripId= '" & ThisTripID & "' "
Command = New SqlCommand(Query, MyCon)
Command.ExecuteNonQuery()
MyCon.Close()
failed_to_upload = False
MsgBox("Trip ID: " & ThisTripID & " at '" & ScanPointName & "' saved successfully")
Catch ex As Exception
MsgBox(ex.Message)
failed_to_upload = True
MsgBox("The uploading process could NOT be completed properly due to network issue.
The Trip ID '" & ThisTripID & "' of '" & ScanPointName & "' may not include checked orders or items correctly. Therefor please contact system administrator with following details to roll back this event immediately.
Trip ID = '" & ThisTripID & "'
Scan Point = '" & ScanPointName & "'")
End Try
End Sub

MS Access 2010 VBA Integer Variable not changing in Loop

I have code that is looping through an array of member numbers and retrieving records for each. Each time, I need to use the count of the records returned up to 12. However, once the variable that is to hold the count is set, it will not reset with the next call. It also "jumps" from the first to the last record rather than looping through each. In other words, if there are 4 records returned by the recordset, it will execute for the first and the last and then give an error of "No Current Record" Here is my code:
Dim x As Integer
For i = 1 To intMembers
strGetMemberInfo = "SELECT PatientRecords.[Medication Name], PatientRecords.[First Name], PatientRecords.[Last Name],PatientRecords.[doc phone]" _
& " FROM PatientRecords WHERE member_no ='" & arrMembers(i) & "'"
Set rstMedicine = dbs.OpenRecordset(strGetMemberInfo, dbOpenSnapshot)
Dim intMedicine As Integer
intMedicine = rstMedicine.RecordCount
If intMedicine > 12 Then
intMedicine = 12
End If
Do Until rstMedicine.EOF
For x = 1 To intMedicine
strMedicationField = strMedication & x
strDoctorFNameField = strDoctorFName & x
strDoctorLNameField = strDocotrLName & x
strDoctorPhoneField = strDoctorPhone & x
strSQL = "UPDATE TransformationTable SET " & strMedicationField & " = '" & rstMedicine.Fields("[Medication Name]").Value & "'," & strDoctorFNameField & " = '" & rstMedicine.Fields("[First Name]").Value & "', " & strDoctorLNameField & " = '" & Replace(rstMedicine.Fields("[Last Name]"), "'", "''") & "', " & strDoctorPhoneField & " = '" & rstMedicine.Fields("[doc phone]").Value & "' WHERE member_no ='" & arrMembers(i) & "'"
dbs.Execute strSQL
rstMedicine.MoveNext
Next x
Loop
rstMedicine.Close
Set rstMedicine = Nothing
Next i
In the above code, intMedicinegets set by the first recordset and NEVER changes even though rstMedicine.RecordCount does change.
Any help is appreciated
You have 2 different issues. First, use rstMedicine.MoveLast to move to the bottom of the recordset and get the full count. Second. Your limiting the number of "cycles" to 12, but you are not exiting the loop after intMedicine is 12, so it is still trying to get to the end of the recordset because your code says "Do Until rstMedicine.EOF". Change your code to this:
Dim x As Integer
For i = 1 To intMembers
strGetMemberInfo = "SELECT PatientRecords.[Medication Name], PatientRecords.[First Name], PatientRecords.[Last Name],PatientRecords.[doc phone]" _
& " FROM PatientRecords WHERE member_no ='" & arrMembers(i) & "'"
Set rstMedicine = dbs.OpenRecordset(strGetMemberInfo, dbOpenSnapshot)
rstMedicine.MoveLast
Dim intMedicine As Integer
intMedicine = rstMedicine.RecordCount
If intMedicine > 12 Then
intMedicine = 12
End If
rstMedicine.MoveFirst
Do Until rstMedicine.EOF
For x = 1 To intMedicine
strMedicationField = strMedication & x
strDoctorFNameField = strDoctorFName & x
strDoctorLNameField = strDocotrLName & x
strDoctorPhoneField = strDoctorPhone & x
strSQL = "UPDATE TransformationTable SET " & strMedicationField & " = '" & rstMedicine.Fields("[Medication Name]").Value & "'," & strDoctorFNameField & " = '" & rstMedicine.Fields("[First Name]").Value & "', " & strDoctorLNameField & " = '" & Replace(rstMedicine.Fields("[Last Name]"), "'", "''") & "', " & strDoctorPhoneField & " = '" & rstMedicine.Fields("[doc phone]").Value & "' WHERE member_no ='" & arrMembers(i) & "'"
dbs.Execute strSQL
rstMedicine.MoveNext
If x = 12 Then
Exit Do
End If
Next x
Loop
rstMedicine.Close
Set rstMedicine = Nothing
Next i

How do I update multiple table column value of database using textboxes in VB.NET?

Here is my code. But It is not working on multiple update of table values, It only does work when I update a single value. please help me, im newbie here :(
Private Sub SaveChanges_Click(sender As System.Object, e As System.EventArgs) Handles SaveChanges.Click
Dim con As New MySqlConnection("host = localhost; username = root; password = 1234; database = logindb")
Dim cmd As New MySqlCommand
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE login SET username = '" & ChangeUsername.Text & "' and password = '" & ChangePassword.Text & "' and Security_Question1 ='" & ChangeSecQue1.Text & "' and Security_Question2 = '" & ChangeSecQue2.Text & "' and Security_Answer1 = '" & ChangeSecAns1.Text & "' and Security_Answer2 = '" & ChangeSecAns2.Text & "' "
cmd.ExecuteNonQuery()
MsgBox("Saved Changes!")
con.Close()
End Sub
change your update statement:
cmd.CommandText = "UPDATE login SET username = '" & ChangeUsername.Text & "' ,password = '" & ChangePassword.Text & "' ,Security_Question1 ='" & ChangeSecQue1.Text & "' ,Security_Question2 = '" & ChangeSecQue2.Text & "' ,Security_Answer1 = '" & ChangeSecAns1.Text & "' ,Security_Answer2 = '" & ChangeSecAns2.Text & "' "