i have application i want it to do
1- insert the first statement .
2-get the (maxid) of the invoice
3-insert the detail of the invoice with the Id .
it give me this error
index out of range .
Private Sub insert()
Dim invoiceday As Date = Today
Dim userid As Integer
Dim clientid As Integer
Dim note As String
If clients.Visible = True Then
userid = 1
clientid = 2
note = "cash"
Else
userid = 2
clientid = 6
note = "credit"
End If
Dim query1 As String = " insert into invoices([purchasedate],clientid,[Note],userID,total,disq) Values ( '" & CDate(invoiceday) & "','" & clientid & "','" & note & "','" & userid & "','" & totalprice.Text & "','" & txtdis.Text & "')"
samselect2(query1)
Dim maxinvoice As Integer
maxinvoice = invoiceid()
For Each row As DataGridViewRow In dvsale.Rows
Dim query As String = " insert into invoicede(invoiceid,barcode,doaname,Qty,Price,qtyprice) Values ('" & maxinvoice + 1 & "','" & row.Cells("barcode").Value & "','" & row.Cells("doaname").Value & "','" & row.Cells("qty").Value & "','" & row.Cells("price").Value & "','" & row.Cells("tqty").Value & "')"
samselect2(query)
Next
End Sub
this the class of the samselect2
Public Sub samselect2(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
End Try
con.Close()
da.Dispose()
End Sub
and the invoiceid max number
Private Function invoiceid()
checkConnection()
Dim strQ As String = "SELECT max(invoiceID)as MaxIDbatch from invoices "
Dim cmdQ As OleDbCommand = New OleDbCommand(strQ, con)
Dim result = cmdQ.ExecuteScalar()
If result IsNot Nothing Then
Dim x As Integer = 0
Return x
Else
Return result
End If
End Function
Although I don't fully understand your question, I notice a couple things: 1) It appears that InvoiceID is not an auto-incrementing identity field, and it probably should be. (Check out "Is Identity".) If it were, you could insert and specify all fields except that one, and the number would increment automatically. 2) In your for...each, you are not increasing maxinvoice at all with each iteration through the loop. Although you're using maxinvoice+1, it will still be the same number each time.
Still, all of that should be unnecessary if you make InvoiceID an identity field.
Related
Apologies for the vague title, but here is my issue. I have a form that has several select lists and associated text boxes. Basically the way it works is if you select a name from the first list, an AfterUpdate event is triggered to query the DB to see if the Eng_ID and Person_ID already exist in the table. If so, then delete that row then insert the updated row. If there is not any records, then just insert the data. The problem is that when I click a name in the first list, then move to the second list, what's happening is that the the Person_ID of the first list is used for the DLookup query, then it delets the record, then inserts the record of the new person I selected in a different listbox. The code is below: Thanks in advance
' Add/Remove Participant 1
Private Sub lstPar1_AfterUpdate()
Dim n As Integer
Dim strCriteria As String
Dim strSQL As String
With Me.lstPar1
For n = .ListCount - 1 To 0 Step -1
strCriteria = "Eng_ID = " & Nz(Me.Eng_ID, 0) & " And Person_ID = " & .ItemData(n)
If .Selected(n) = False Then
' If a person has been deselected, then delete row from table
If Not IsNull(DLookup("Eng_ID", "tblEngParRole", strCriteria)) Then
strSQL = "DELETE * FROM tblEngParRole WHERE " & strCriteria
CurrentDb.Execute strSQL, dbFailOnError
End If
Else
' If a person has been selected, then insert row into the table
If IsNull(DLookup("Eng_ID", "tblEngParRole", strCriteria)) Then
strSQL = "INSERT INTO tblEngParRole (Eng_ID, Person_ID, ParticipantNumber, Role)" & "VALUES(" & Me.Eng_ID & "," & .ItemData(n) & "," & 1 & ",'" & Me.txtParRole1.Value & "' )"
CurrentDb.Execute strSQL, dbFailOnError
End If
End If
Next n
End With
End Sub
' Add/Remove Participant 2
Private Sub lstPar2_AfterUpdate()
Dim n As Integer
Dim strCriteria As String
Dim strSQL As String
With Me.lstPar2
For n = .ListCount - 1 To 0 Step -1
strCriteria = "Eng_ID = " & Nz(Me.Eng_ID, 0) & " And Person_ID = " & .ItemData(n)
If .Selected(n) = False Then
' If a person has been deselected, then delete row from table
If Not IsNull(DLookup("Eng_ID", "tblEngParRole", strCriteria)) Then
strSQL = "DELETE * FROM tblEngParRole WHERE " & strCriteria
CurrentDb.Execute strSQL, dbFailOnError
End If
Else
' If a person has been selected, then insert row into the table
If IsNull(DLookup("Eng_ID", "tblEngParRole", strCriteria)) Then
strSQL = "INSERT INTO tblEngParRole (Eng_ID, Person_ID, ParticipantNumber, Role) " & "VALUES(" & Me.Eng_ID & "," & .ItemData(n) & "," & 2 & ",'" & Me.txtParRole2.Value & "' )"
CurrentDb.Execute strSQL, dbFailOnError
End If
End If
Next n
End With
End Sub
Using this image, if I select Daniel and enter his role, then the eng_ID, Person_ID, ParticipantNumber and Role are entered into the database as 130, 118, 1, Collaborator.
If I select Kristin, it deletes Daniel becuause it's still using Person_ID of 118 instead of hers which is 134, and since there is a corresponding record, it delets Daniel then adds Kristin.
I don't have Access to test this with, but it seems like you need to separate Participant1 records from Participant2 records when you perform your DLookups.
Also you can generalize your code by pulling the common parts into a separate sub.
Private Sub lstPar1_AfterUpdate()
CheckParticipant Me.lstPar1, 1, Me.txtParRole1.Value
End Sub
Private Sub lstPar2_AfterUpdate()
CheckParticipant Me.lstPar2, 2, Me.txtParRole2.Value
End Sub
Sub CheckParticipant(objList As Object, participantNum As Long, role As String)
Dim n As Integer
Dim strCriteria As String
Dim strSQL As String
With objList
For n = .ListCount - 1 To 0 Step -1
strCriteria = "Eng_ID = " & Nz(Me.Eng_ID, 0) & " And Person_ID = " & .ItemData(n) & _
" And ParticipantNumber=" & participantNum
strSQL = ""
If Not .Selected(n) Then
' If a person has been deselected, then delete row from table
If Not IsNull(DLookup("Eng_ID", "tblEngParRole", strCriteria)) Then
strSQL = "DELETE * FROM tblEngParRole WHERE " & strCriteria
End If
Else
' If a person has been selected, then insert row into the table
If IsNull(DLookup("Eng_ID", "tblEngParRole", strCriteria)) Then
strSQL = "INSERT INTO tblEngParRole (Eng_ID, Person_ID, ParticipantNumber, Role)" & _
" VALUES(" & Me.Eng_ID & "," & .ItemData(n) & "," & participantNum & _
",'" & role & "' )"
End If
End If
If Len(strSQL) > 0 Then CurrentDb.Execute strSQL, dbFailOnError
Next n
End With
End Sub
Private Sub btnAddInfo_Click()
On Error GoTo Error_Routine
'Declare variables
Dim intStudentID As Integer
Dim intTestID As Integer
Dim dblMark As Double
Dim intResultID As Integer
'Declare database
Dim db As DAO.Database
Dim rst As DAO.Recordset
'Set the database
Set db = CurrentDb
Set rst = db.OpenRecordset("Select ResultId FROM StudentResult ORDER BY RESULTID DESC", dbOpenDynaset)
'assign value to intResultID variable
intResultID = rst!ResultId
'Adds the additional 1 to the latest result id that was used
If Not rst.EOF Then
intResultID = intResultID + 1
End If
'Assigns value to variables
intStudentID = Forms!frmAdd!lstStudentID
strDescription = Forms!frmAdd!lstTest
dblMark = txtMark.Value
intTestID = Forms!frmAdd!lstTest
'Checks that Student ID has been selected
If Not IsNull(lstStudentID) Then
'Inserts new test record into StudentResult table
db.Execute "INSERT INTO StudentResult " _
& "(ResultId,StudentId,TestId, Mark) VALUES " _
& "('" & intResultID & "','" & intStudentID & "','" & intTestID & "','" & dblMark & "');"
End If
'Clears fields
txtMark.Value = ""
lstStudentID.Value = ""
lblExistingStudent.Caption = "Existing Student Name:"
'Closes database
Set db = Nothing
I'm trying to add new records. There is a list of 4 tests. ResultId is the primary key and it is an AutoNumber column.
The button adds tests scores just fine if the selected StudentID has not added a score for that TestId yet. But when I try to add a StudentId and TestId combination that has been entered before, it does not add a new record or even update the existing one.
Both StudentId and TestId allow duplicates. I've tried doing this counter variable but it has not worked. This is for a class and the professor says a student should be able to retake tests and it should just add a new record.
Thank you in advance for your help. Please let me know if you need any pictures of the form, tables, or more of my code.
Exclude the AutoNumber field, and don't wrap numbers in quotes:
If Not IsNull(lstStudentID) Then
' Verify values:
Debug.Print "StudentID:", intStudentID, "TestID:", intTestID, "Mark:", Str(dblMark)
'Inserts new test record into StudentResult table
db.Execute "INSERT INTO StudentResult " _
& "(StudentId, TestId, Mark) VALUES " _
& "(" & intStudentID & "," & intTestID & "," & Str(dblMark) & ");"
End If
when i insert data through datagrid in a database data's are inserting but an additional blank row is also coming in the data base
My Code:-
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con()
Dim SNo As String
Dim Name As String
Dim Address As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows.Count = 0 Then
Exit For
End If
SNo = Me.DataGridView1.Rows(i).Cells(0).Value
Name = Me.DataGridView1.Rows(i).Cells(1).Value
Address = Me.DataGridView1.Rows(i).Cells(2).Value
Dim sql As String = "insert into Customer(SNo,Name,Address)values('" & SNo & "','" & Name & "','" & Address & "')"
cmd = New SqlCommand(sql, cn)
cmd.ExecuteNonQuery()
Next
MsgBox("Inserted")
cn.Close()
End Sub
Execute the loop till Datagridview1.rows.count-2
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 2
If Me.DataGridView1.Rows.Count = 0 Then
Exit For
End If
SNo = Me.DataGridView1.Rows(i).Cells(0).Value
Name = Me.DataGridView1.Rows(i).Cells(1).Value
Address = Me.DataGridView1.Rows(i).Cells(2).Value
Dim sql As String = "insert into Customer(SNo,Name,Address)values('" & SNo & "','" & Name & "','" & Address & "')"
cmd = New SqlCommand(sql, cn)
cmd.ExecuteNonQuery()
Next
Please could you help me sort this by 2nd column descending?
Dim ds As New DataSet()
conn.Open()
techSpeciality = LB_techFaultType.Text
techZone = LB_TechZone.Text
Dim strSQL As String = "SELECT Tech_ID, Last_Zone FROM Technician_List WHERE Availability=TRUE AND Speciality='" & techSpeciality & "' AND Last_Zone='" & techZone & "'"
Dim da As New OleDbDataAdapter(strSQL, conn)
da.Fill(ds)
'2D array
Dim values(ds.Tables(0).Rows.Count - 1, 2) As Integer
'for loop between 0 and all available technicians
For value As Integer = 0 To ds.Tables(0).Rows.Count - 1
'Tech_ID column
values(value, 0) = ds.Tables(0).Rows(value).Item(0).value()
'Zone column, converts negative value to a positive and minus' the selected techZone
Math.Abs(values(value, 1) = techZone - ds.Tables(0).Rows(value).Item(1).value())
Next
Modify this line:
Dim strSQL As String = "SELECT Tech_ID, Last_Zone" & _
" FROM Technician_List WHERE" & _
" Availability=TRUE AND Speciality='" & techSpeciality & _
"' AND Last_Zone='" & techZone & _
"' ORDER BY Last_Zone DESC"
For more information on the ORDER BY keywords:
http://www.w3schools.com/sql/sql_orderby.asp
Another option is to do ORDER BY 2 DESC, instead of directly specifying the column name.
Good day guys, I have a question. When I try to use this piece of code in my program which will add a supplier to the database, I encounter data type mismatch error. As far as I know, the status of the supplier creates the error.
How would I store the values of the radio buttons named radActive and radInactive in the database? Should I use Boolean or a String? I am using Microsoft Access as my database and the field of Status is set to Yes/No.
Here's the code.
Public Sub SupplierInsertData()
Dim conn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Dim SupplierType As String
Dim Status As Boolean
'Check for supplier type
If frmDatabaseSupplier.radLocal.Checked = True Then
SupplierType = "Local"
ElseIf frmDatabaseSupplier.radForeign.Checked = True Then
SupplierType = "Foreign"
End If
'Check for supplier status
If frmDatabaseSupplier.radActive.Checked = True Then
Status = True
ElseIf frmDatabaseSupplier.radInactive.Checked = True Then
Status = False
End If
'For inserting of data in the database.
Dim cmdString As String = "INSERT INTO Supplier(SupplierLastName, SupplierFirstName, SupplierMiddleInitial, " & _
"SupplierCompany, SupplierType, SupplierStreetAddress, SupplierCity, SupplierContactNumber, SupplierEmail, " & _
"Status)" & _
"VALUES('" & frmDatabaseSupplier.txtSupplierLastName.Text & "','" & frmDatabaseSupplier.txtSupplierFirstName.Text & "','" & frmDatabaseSupplier.txtSupplierMiddleInitial.Text & "','" _
& frmDatabaseSupplier.txtSupplierCompany.Text & "','" & SupplierType & "', '" & frmDatabaseSupplier.txtSupplierStreetAddress.Text & "','" & frmDatabaseSupplier.txtSupplierCity.Text & "','" _
& frmDatabaseSupplier.txtSupplierContactNumber.Text & "','" & frmDatabaseSupplier.txtSupplierEmail.Text & "','" & Status & "')"
conn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectAnalysisSystem.accdb")
cmd = New OleDb.OleDbCommand(cmdString, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
Thank you!
Try to change the last part of your code.
You should use parameters to pass the values of your textbox or vars to the database engine.
And don't forget to encapsulate the disposable objects like OleDbConnection in a using statement.
Dim cmdString As String = "INSERT INTO Supplier(SupplierLastName, SupplierFirstName, SupplierMiddleInitial, " & _
"SupplierCompany, SupplierType, SupplierStreetAddress, SupplierCity, SupplierContactNumber, SupplierEmail, " & _
"Status)" & _
"VALUES(#supplierName, #supplierFirst, #supplierMiddle, #supplierCo, #supplierType, #supplierStreet, #supplierCity, " & _
"#supplierContact, #supplierMail, #status)"
Using conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectAnalysisSystem.accdb")
Dim cmd As OleDbCommand = New OleDb.OleDbCommand(cmdString, conn))
cmd.Parameters.AddWithValue("#supplierName", frmDatabaseSupplier.txtSupplierLastName.Text)
cmd.Parameters.AddWithValue("#supplierFirst", frmDatabaseSupplier.txtSupplierFirstName.Text)
cmd.Parameters.AddWithValue("#supplierMiddle", frmDatabaseSupplier.txtSupplierMiddleInitial.Text)
cmd.Parameters.AddWithValue("#supplierCo", frmDatabaseSupplier.txtSupplierCompany.Text )
cmd.Parameters.AddWithValue("#supplierType", SupplierType)
cmd.Parameters.AddWithValue("#supplierStreet", frmDatabaseSupplier.txtSupplierStreetAddress.Text)
cmd.Parameters.AddWithValue("#supplierCity", frmDatabaseSupplier.txtSupplierCity.Text)
cmd.Parameters.AddWithValue("#supplierContact", frmDatabaseSupplier.txtSupplierContactNumber.Text)
cmd.Parameters.AddWithValue("#supplierMail", frmDatabaseSupplier.txtSupplierEmail.Text)
cmd.Parameters.AddWithValue("#status", Status) '<- Here the status var is correctly identified as a boolean, not as a string
conn.Open()
cmd.ExecuteNonQuery()
End Using
You have a data type mismatch error because your INSERT statement attempts to store a string value for the Status field whose data type is Yes/No.
This isn't really a VB.Net problem. You would get the very same error from Access' db engine if you were attempting the same thing from VBA. This is the output from the VBA procedure below.
INSERT INTO Supplier (Status)
VALUES('True')
Error -2147217913 (Data type mismatch in criteria expression.)
The procedure ...
Public Sub Ju_chan()
Dim cmdString As String
Dim Status As Boolean
Dim strMsg As String
On Error GoTo ErrorHandler
Status = True
cmdString = "INSERT INTO Supplier (Status)" & vbCrLf & _
"VALUES('" & Status & "')"
Debug.Print cmdString
CurrentProject.Connection.Execute cmdString
ExitHere:
On Error GoTo 0
Exit Sub
ErrorHandler:
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ")"
Debug.Print strMsg
GoTo ExitHere
End Sub
Please understand this is not intended to steer you away from using parameters. I only wanted to clarify why you're getting that error.