How do I reference X controls into a FOR loop? - vb.net

I have those three text boxes by the name StandardPath_TextBoxA1, StandardPath_TextBoxA2, StandardPath_TextBoxA3 and through a FOR loop I am trying to save their text values into an ms access database file. I am trying something like this below, but my syntax is wrong... Any idea?
For i = 1 To 3
Dim str(i) As String
str(i) = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str(i), MyConnection)
cmd.Parameters.Add(New OleDbParameter("TagNum", CType("A" & i, String)))
cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
EDIT:
The syntax error located here:
cmd.Parameters.Add(New OleDbParameter("Title", CType(StandardPath_LabelA(i).Text), String)))
cmd.Parameters.Add(New OleDbParameter("Path", CType(StandardPath_TextBoxA(i).Text), String)))

Try this. It fixes some type-mismatches in the original, as well as removing unnecessary variables and redundancy.
Dim sql As String = "INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?)"
'DON'T RE-USE YOUR DATABASE CONNECTION, EXCEPT FOR SHORT BURSTS IN TIGHT LOOPS LIKE THIS
Using connection As New OleDbConnection("connection string here"), _
cmd As New OleDbCommand(sql, connection)
'Guessing at column types and lengths. Use actual types from your database here
cmd.Parameters.Add("TagNum", OleDbType.VarChar, 2)
cmd.Parameters.Add("Title", OleDbType.VarWChar, 100)
cmd.Parameters.Add("Path", OleDbType.VarWChar, 512)
'Do this just once, outside the loop, to avoid needing to repeatedly re-negotiate with the DB. Let the USING black take care of closing the connection
connection.Open()
For i = 1 To 3
Dim TitleLabel As Control = Me.Controls.Find("StandardPath_LabelA" & i.ToString(), True).First()
Dim PathBox As Control = Me.Controls.Find("StandardPath_TextBoxA" & i.ToString(), True).First()
cmd.Parameters(0).Value = "A" & i.ToString()
cmd.Parameters(1).Value = TitleLabel.Text
cmd.Parameters(2).Value = PathBox.Text
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
End Using
Even better if you have already grouped these controls in related panel or similar control, or added them to an array. That could allow better options than Controls.Find(), but I saw no indication of this in the question.
One other option, since the number of items is small, is to do it like this:
Dim sql As String = _
"INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
"INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);" & VbCrLf & _
"INSERT INTO StandardPaths ([TagNum], [Title], [Path]) values (?,?,?);"
Using connection As New OleDbConnection("connection string here"), _
cmd As New OleDbCommand(sql, connection)
'Guessing at column types and lengths. Use actual types from your database here
cmd.Parameters.Add("TagNum1", OleDbType.VarChar, 2).Value = "A1"
cmd.Parameters.Add("Title1", OleDbType.VarWChar, 100).Value = StandardPath_LabelA1.Text
cmd.Parameters.Add("Path1", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA1.Text
cmd.Parameters.Add("TagNum2", OleDbType.VarChar, 2).Value = "A2"
cmd.Parameters.Add("Title2", OleDbType.VarWChar, 100).Value = StandardPath_LabelA2.Text
cmd.Parameters.Add("Path2", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA2.Text
cmd.Parameters.Add("TagNum3", OleDbType.VarChar, 2).Value = "A3"
cmd.Parameters.Add("Title3", OleDbType.VarWChar, 100).Value = StandardPath_LabelA3.Text
cmd.Parameters.Add("Path3", OleDbType.VarWChar, 512).Value = StandardPath_TextBoxA3.Text
connection.Open()
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
I know the repeated code is often seen as bad, but for three items sometimes a loop is just overkill. In this case, skipping the loop also gives an advantage of reducing you to a single atomic trip to the database.

Related

How to use VB and SQL to add Records to a Relational Database in Access

I'm working in Visual Basic to create a forms applications as part of a college project. I've used SQL statements to read from the access database but I'm having some trouble writing to it. I'd like to hazard a guess it's due to the database having relationships between tables.
This is my first go at making something substantial, and vb is not my language of choice. Expect the code to be poor at best. If anyone has links to resources that I could use to improve I'd be immensely grateful.
Exception:
Exception thrown: 'System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
Exception location: 'commAddToStaff.ExecuteNonQuery()'
Both try statements are catching exceptions when ran. I've attempted providing data in the parameters rather than using data from a text box, but this hasn't resolved the issue.
Code:
Private Sub btnAddStaffMember_Click(sender As Object, e As EventArgs) Handles btnAddStaffMember.Click
'Dimension tblStaff Parameters
Dim AddEmployeeIDParam As New OleDb.OleDbParameter("#AddEmployeeID", txtAddEmployeeID.Text)
Dim AddForenameParam As New OleDb.OleDbParameter("#AddForename", txtAddForename.Text)
Dim AddSurnameParam As New OleDb.OleDbParameter("#AddSurname", txtAddSurname.Text)
Dim AddDOBParam As New OleDb.OleDbParameter("#AddDOB", txtAddDOB.Text)
Dim AddUserTierParam As New OleDb.OleDbParameter("#AddUserTier", txtAddUserTier.Text)
'Dimension tblContacts Parameters
Dim conContact As New OleDb.OleDbConnection("Provider=Microsoft.......")
Dim commContactCount As New OleDb.OleDbCommand("Select Count(*) FROM tblContacts", conContact)
commContactCount.Connection.Open()
Dim ContactID = commContactCount.ExecuteScalar + 1 'Calculate the contactID of the new record
commContactCount.Connection.Close() 'Close the connection
Dim AddContactIDParam As New OleDb.OleDbParameter("#AddContactID", ContactID)
Dim AddAddressParam As New OleDb.OleDbParameter("#AddAddress", txtAddAddress.Text)
Dim AddPostcodeParam As New OleDb.OleDbParameter("#AddPostcode", txtAddPostcode.Text)
Dim AddEmailParam As New OleDb.OleDbParameter("#AddEmail", txtAddEmail.Text)
Dim AddMobileNoParam As New OleDb.OleDbParameter("#AddMobileNo", txtAddMobileNumber.Text)
Dim conAddToStaff As New OleDb.OleDbConnection("Provider=Microsoft....")
Dim commAddToStaff As New OleDb.OleDbCommand("Insert Into tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)", conAddToStaff)
commAddToStaff.Parameters.Add(AddEmployeeIDParam)
commAddToStaff.Parameters.Add(AddForenameParam)
commAddToStaff.Parameters.Add(AddSurnameParam)
commAddToStaff.Parameters.Add(AddDOBParam)
commAddToStaff.Parameters.Add(AddUserTierParam)
Dim commAddToContact As New OleDb.OleDbCommand("Insert Into tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) Values (#AddContactID, #AddAddress, #AddPostcode, #AddEmail, #AddMobileNo)", conContact)
commAddToContact.Parameters.Add(AddContactIDParam)
commAddToContact.Parameters.Add(AddAddressParam)
commAddToContact.Parameters.Add(AddPostcodeParam)
commAddToContact.Parameters.Add(AddEmailParam)
commAddToContact.Parameters.Add(AddMobileNoParam)
Try
commAddToStaff.Connection.Open() 'Open a connection to the database
commAddToStaff.ExecuteNonQuery() 'Execute the command
commAddToStaff.Connection.Dispose() 'Remove unmanaged resources
commAddToStaff.Connection.Close() 'Close the connection
Catch ex As Exception
MessageBox.Show("Error with staff")
End Try
Try
commAddToContact.Connection.Open() 'Open a connection to the database
commAddToContact.ExecuteNonQuery() 'Execute the command
commAddToContact.Connection.Dispose() 'Remove unmanaged resources
commAddToContact.Connection.Close() 'Close the connection
Catch ex As Exception
MessageBox.Show("Error with contacts")
End Try
MessageBox.Show("Reached")
Me.Hide() 'Close the Current screen
StaffDB_Add_Staff_Security_Question.Show() 'Open the Add Security Question Screen
End Sub
You are inserting six values into six columns here:
Dim commAddToStaff As New OleDb.OleDbCommand("Insert Into tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)", conAddToStaff)
but you only add five parameters to the command here:
commAddToStaff.Parameters.Add(AddEmployeeIDParam)
commAddToStaff.Parameters.Add(AddForenameParam)
commAddToStaff.Parameters.Add(AddSurnameParam)
commAddToStaff.Parameters.Add(AddDOBParam)
commAddToStaff.Parameters.Add(AddUserTierParam)
Where's the parameter for the #AddContactID placeholder in the SQL code?
EDIT:
For the record, here's how I would tend to write code for that sort of task, ignoring the horrible way you're generating the ContactID value:
Using connection As New OleDbConnection("connection string here")
connection.Open()
Dim contactCount As Integer
Using contactCountCommand As New OleDbCommand("SELECT COUNT(*) FROM tblContacts", connection)
contactCount = CInt(contactCountCommand.ExecuteScalar())
End Using
Dim contactId = contactCount + 1
Using staffCommand As New OleDbCommand("INSERT INTO tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#EmployeeID, #Forename, #Surname, #DOB, #User_Tier, #ContactID)", connection)
With staffCommand.Parameters
.Add("#EmployeeID", OleDbType.VarChar, 50).Value = txtAddEmployeeID.Text
.Add("#Forename", OleDbType.VarChar, 50).Value = txtAddForename.Text
.Add("#Surname", OleDbType.VarChar, 50).Value = txtAddSurname.Text
.Add("#DOB", OleDbType.Date).Value = CDate(txtAddDOB.Text) 'Why isn't this coming from a DateTimePicker?
.Add("#User_Tier", OleDbType.VarChar, 50).Value = txtAddUserTier.Text
.Add("#ContactID", OleDbType.Integer).Value = contactId
End With
staffCommand.ExecuteNonQuery()
End Using
Using contactCommand As New OleDbCommand("INSERT INTO tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) Values (#ContactID, #Address, #Postcode, #Email, #Mobile_Number)", connection)
With contactCommand.Parameters
.Add("#ContactID", OleDbType.Integer).Value = contactId
.Add("#Address", OleDbType.VarChar, 50).Value = txtAddAddress.Text
.Add("#Postcode", OleDbType.VarChar, 50).Value = txtAddPostcode.Text
.Add("#Email", OleDbType.VarChar, 50).Value = txtAddEmail.Text
.Add("#Mobile_Number", OleDbType.VarChar, 50).Value = txtAddMobileNumber.Text
End With
contactCommand.ExecuteNonQuery()
End Using
End Using
It would be easier to see where there are insufficient parameters added by rearranging the code into smaller pieces, where related items are near to each other. Something like:
Imports System.Data.OleDb
Public Class Form1
Dim connStr As String = "Provider=Microsoft......."
Sub AddStaffMemberToDatabase(contactId As Integer)
Dim sql = "INSERT INTO tblStaff (EmployeeID, Forename, Surname, DOB, UserTier, ContactID) VALUES (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)"
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
Dim dob = DateTime.Parse(txtAddDOB.Text)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddEmployeeID", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddEmployeeID.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddForename", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddForename.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddSurname", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddSurname.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddDOB", .OleDbType = OleDbType.Date, .Value = dob})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddUserTier", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddUserTier.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddContactID", .OleDbType = OleDbType.Integer, .Value = contactId})
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Sub AddContactToDatabase(contactId As Integer)
Dim sql = "INSERT INTO tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) VALUES (#AddContactID, #AddAddress, #AddPostcode, #AddEmail, #AddMobileNo)"
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddContactID", .OleDbType = OleDbType.Integer, .Value = contactId})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddAddress", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddAddress.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#txtAddPostcode", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddPostcode.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddEmail", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddEmail.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddMobileNo", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddMobileNumber.Text})
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Sub AddStaffMember()
Dim sql = "SELECT COUNT(*) FROM tblContacts"
Dim contactID As Integer
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
conn.Open()
contactID = Convert.ToInt32(cmd.ExecuteScalar()) + 1
End Using
AddStaffMemberToDatabase(contactID)
AddContactToDatabase(contactID)
End Sub
Private Sub btnAddStaffMember_Click(sender As Object, e As EventArgs) Handles btnAddStaffMember.Click
AddStaffMember()
Me.Hide()
StaffDB_Add_Staff_Security_Question.Show() 'Open the Add Security Question Screen
End Sub
End Class
The Using statement makes sure that "unamanaged resources" are released when the code has finished with them.
Note that you will need to provide a more specific and robust way of parsing the DOB text (e.g. DateTime.TryParseExact). Also, the database types and sizes need to be edited to match the declarations in the database.

Insert string into different tables based on combobox selection

1st off, my apologies if this question has been asked. I have looked but haven't found an exact answer to the problem I'm facing. Secondly, I must stress that, I am not a developer, I'm an engineer and only writing sowftware as a needs must situation.
I have a form which passes data to an access db (This works). However I need to update it so that it will pass the information to different tables within the same db based upon a selection in a combobox. For instance if combobox selection = X then insert into tableX, if combobox = Y then insert into tableY. Any and all help is appreciated.
I've tried using If statements in order to select the appropriate table, but this doesn't work.
Imports System.Data.OleDb
Public Class Form1
Public ds As New DataSet
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim rs As New resizer
Dim cmd As OleDbCommand
Private con As Object
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
provider = "Provider=Microsoft.Jet.OleDb.4.0;Data Source="
dataFile = "R:\Quality\NCR-Access_Database\NCRdb1.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = ""
If ComboBox2.SelectedText = "Assembly" Then
str = "Insert into [ASSEMBLYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Grinding" Then
str = "Insert into [GRINDINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Milling" Then
str = "Insert into [MILLINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Mill-Turn" Then
str = "Insert into [MILL-TURNtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Turning" Then
str = "Insert into [TURNINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Supplier" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Subcon" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Quality" Then
str = "Insert into [QUALITYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
End If
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("NCR-No", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Week-No", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("Part-No", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("Drawing_Rev", TextBox5.Text))
cmd.Parameters.Add(New OleDbParameter("Description", TextBox6.Text))
cmd.Parameters.Add(New OleDbParameter("W/O-No", TextBox7.Text))
cmd.Parameters.Add(New OleDbParameter("Operator-No", TextBox8.Text))
cmd.Parameters.Add(New OleDbParameter("Operation-No", TextBox9.Text))
cmd.Parameters.Add(New OleDbParameter("Machine-No", TextBox10.Text))
cmd.Parameters.Add(New OleDbParameter("Section", ComboBox2.Text))
cmd.Parameters.Add(New OleDbParameter("Batch-Qty", TextBox12.Text))
cmd.Parameters.Add(New OleDbParameter("Reject_Qty", TextBox13.Text))
cmd.Parameters.Add(New OleDbParameter("Disposition", TextBox14.Text))
cmd.Parameters.Add(New OleDbParameter("Mat-Cost", TextBox15.Text))
cmd.Parameters.Add(New OleDbParameter("Standard-Cost", TextBox16.Text))
cmd.Parameters.Add(New OleDbParameter("Defect-Description", RichTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Fault-Code", TextBox17.Text))
cmd.Parameters.Add(New OleDbParameter("Dept", TextBox18.Text))
cmd.Parameters.Add(New OleDbParameter("Root-Cause", RichTextBox2.Text))
cmd.Parameters.Add(New OleDbParameter("NCR-Pinksheet", ComboBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Permanent-Action", RichTextBox3.Text))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox1.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox3.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
ComboBox2.ResetText()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
RichTextBox1.Clear()
TextBox17.Clear()
TextBox18.Clear()
RichTextBox2.Clear()
ComboBox1.ResetText()
RichTextBox3.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
When submitting I get a dialog that states "Command text was not set for the command object". If i submit again, then I get an exception unhandled event in VS --- "System.InvalidOperationException: 'Not allowed to change the 'ConnectionString' property. The connection's current state is open.'"
use INSERT INTO syntax
INSERT INTO table-name (column-names)
VALUES (values)
SQL INSERT INTO with SELECT like this
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1),
SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100),
City, Country, Phone
FROM Supplier
WHERE CompanyName = 'casterx.co'

How to do two inserts in two different tables in VB.Net

I am trying to execute two different INSERT statements with one click of a button.
But when I try running my code only one of the INSERT statements is working at time.
What is the best way to fix this?
pro = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\XXXX\Desktop\XXXX\XXXXX.mdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
commmand = ("insert into ApplicationData ([lastname], [firstname],[studentbirthday],[gender], [email], [phonenumber], [address], [city], [state], [zip], [dadlastname], [dadfirstname], [momlastname],[momfirstname]) values ('" & NewLastNameText.Text & "', '" & NewFirstNameText.Text & "','" & NewDateTimePicker.Text & "','" & NewGenderText.Text & "','" & NewEmailText.Text & "','" & phone.Text & "','" & NewAddressText.Text & "','" & city.Text & "','" & state.Text & "','" & zip.Text & "','" & NewDadLNtext.Text & "','" & NewDadFNtext.Text & "','" & NewMomLNtext.Text & "','" & NewMomFNtext.Text & "')")
commmand = ("insert into StudentLogin ([username], [password]) values('" & username.Text & "','" & password.Text & "')")
Dim cmd As OleDbCommand = New OleDbCommand(commmand, myconnection)
cmd.Parameters.Add(New OleDbParameter("lastname", CType(NewLastNameText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("firstname", CType(NewFirstNameText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("studentbirthday", CType(NewDateTimePicker.Text, String)))
cmd.Parameters.Add(New OleDbParameter("gender", CType(NewDateTimePicker.Text, String)))
cmd.Parameters.Add(New OleDbParameter("email", CType(NewEmailText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("phonenumber", CType(phone.Text, String)))
cmd.Parameters.Add(New OleDbParameter("address", CType(NewAddressText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("city", CType(city.Text, String)))
cmd.Parameters.Add(New OleDbParameter("state", CType(state.Text, String)))
cmd.Parameters.Add(New OleDbParameter("zip", CType(zip.Text, String)))
cmd.Parameters.Add(New OleDbParameter("dadlastname", CType(NewDadLNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("dadfirstname", CType(NewDadFNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("momfirstname", CType(NewMomLNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("momlastname", CType(NewMomFNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("username", CType(username.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(password.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
MsgBox("Student Added")
NewLastNameText.Clear()
NewFirstNameText.Clear()
NewEmailText.Clear()
NewAddressText.Clear()
NewDadLNtext.Clear()
NewDadFNtext.Clear()
NewMomLNtext.Clear()
NewMomFNtext.Clear()
Catch ex As Exception
End Try
Put both commands into the same string
Dim command1 = "insert into ApplicationData ([lastname], ... values (?, ?, ...)"
Dim command2 = "insert into StudentLogin ([username], ... values (?, ?, ...)"
commmand = command1 & "; " & command2
Btw.: you are adding parameters (which is fine), but did not replace the string concatenation of the commands by parameters. For OLEDB, you have to use positional parameters. I.e., in the SQL text, you have to use a ? for each parameter. Then you have to add the parameters to the parameter collection in the same order! (The name you are using there is ignored, so it does not matter.)
Pass the connection string to the connection when creating it and do not change it afterwards. Always declare the connection in a Using Statement. It automatically closes and disposes the connection at the end. Note, it is not a problem to create new connection objects every time you use one. Because of connection pooling, the "real" connection will be reused.
pro = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\XXXX\Desktop\XXXX\XXXXX.mdb"
Using myconnection As New OleDbConnection(pro)
myconnection.Open()
Dim command1 = "insert into ApplicationData ([lastname], ... values (?, ?, ...)"
Dim command2 = "insert into StudentLogin ([username], ... values (?, ?, ...)"
commmand = command1 & "; " & command2
...
End Using ' Automatically closes connection here.
OleDb does not care about the names or our parameters. It only cares about the order they appear in the Sql statment matches the order they are added to the parameters collection.
Concatenating strings in you Sql statement is a bad idea for several reason and is certainly not needed when you are using parameters. The .Add method of the parameters collection is very clever and returns an OleDb parameter object without us having to declare on explicitly. It is always a good idea to include the OleDb data type.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Pass the connection string directly to the constructor of the connection
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\XXXX\Desktop\XXXX\XXXXX.mdb")
'Pass the Sql statement and the connection directly to the constructor of the command.
'Note: this should NOT be an open connection.
Using StudentCommand As New OleDbCommand("insert into ApplicationData ([lastname], [firstname],[studentbirthday],[gender], [email], [phonenumber], [address], [city], [state], [zip], [dadlastname], [dadfirstname], [momlastname],[momfirstname]) values (lastname, firstname,studentbirthday,gender,email,phonenumber,address,city,state,zip,dadlastname,dadfirstname,momlastname,momfirstname);", cn)
StudentCommand.Parameters.Add("lastname", OleDbType.VarChar).Value = NewLastNameText.Text
StudentCommand.Parameters.Add("firstname", OleDbType.VarChar).Value = NewFirstNameText.Text
StudentCommand.Parameters.Add("studentbirthday", OleDbType.VarChar).Value = NewDateTimePicker.Text
StudentCommand.Parameters.Add("gender", OleDbType.VarChar).Value = NewDateTimePicker.Text
StudentCommand.Parameters.Add("email", OleDbType.VarChar).Value = NewEmailText.Text
StudentCommand.Parameters.Add("phonenumber", OleDbType.VarChar).Value = phone.Text
StudentCommand.Parameters.Add("address", OleDbType.VarChar).Value = NewAddressText.Text
StudentCommand.Parameters.Add("city", OleDbType.VarChar).Value = city.Text
StudentCommand.Parameters.Add("state", OleDbType.VarChar).Value = state.Text
StudentCommand.Parameters.Add("zip", OleDbType.VarChar).Value = zip.Text
StudentCommand.Parameters.Add("dadlastname", OleDbType.VarChar).Value = NewDadLNtext.Text
StudentCommand.Parameters.Add("dadfirstname", OleDbType.VarChar).Value = NewDadFNtext.Text
StudentCommand.Parameters.Add("momfirstname", OleDbType.VarChar).Value = NewMomLNtext.Text
StudentCommand.Parameters.Add("momlastname", OleDbType.VarChar).Value = NewMomFNtext.Text
'Open the connection at the last minute
cn.Open()
StudentCommand.ExecuteNonQuery()
cn.Close()
End Using 'Disposes StudentCommand
Using LoginCommand As New OleDbCommand("insert into StudentLogin ([username], [password]) values(#username, #password;", cn)
LoginCommand.Parameters.Add("#username", OleDbType.VarChar).Value = username.Text
LoginCommand.Parameters.Add("#password", OleDbType.VarChar).Value = password.Text
cn.Open()
LoginCommand.ExecuteNonQuery()
'We don't need to .Close the connection
'The second End Using will close and dispose the connection
End Using 'Disposes LoginCommand
End Using
MessageBox.Show("Student Added")
NewLastNameText.Clear()
NewFirstNameText.Clear()
NewEmailText.Clear()
NewAddressText.Clear()
NewDadLNtext.Clear()
NewDadFNtext.Clear()
NewMomLNtext.Clear()
NewMomFNtext.Clear()
End Sub
One button click, 2 commands executed.
Of course in a real application you would NEVER save passwords as plain text.

Vb.Net 2010 - SQL Insert Command with autonumeric value

I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try

Insert multiple combobox value into one sql column

I need to insert in sql the value of two combobox but I cant seem to make it right.
Data = "INSERT INTO [Mc_Koy].[dbo].[Transaction] ([ID],[Desciption],[Amount]) VALUES ('" & txtbox_id.Text & "','" & cmbo_frm.SelectedValue & &cmbo_to.SelectedValue &"','" & txt_fare.Text & "')"
What you should do is have separate columns in the database for the "From" and "To" values. Also, the Amount column should be a numeric type, preferably a Decimal. You didn't say which database you are using, so I can't give an exact answer, but your SQL and associated VB code should be something like
Dim connStr = "Your SQL connection string here"
Using sqlConn As New SqlConnection(connStr)
Dim sql As String = "INSERT INTO [Mc_Koy].[dbo].[Transaction] ([ID],[FromLocation],[ToLocation],[Amount]) VALUES (#Id, #From, #To, #Fare)"
Dim sqlCmd As New SqlCommand(sql, sqlConn)
'TODO: Set the .Size parameters to match those in the database. '
sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "#Id", .SqlDbType = SqlDbType.VarChar, .Size = 30, .Value = txtbox_id.Text})
sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.VarChar, .Size = 30, .Value = cmbo_frm.SelectedValue})
sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.VarChar, .Size = 30, .Value = cmbo_to.SelectedValue})
sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "#Fare", .SqlDbType = SqlDbType.Decimal, .Value = CDec(txt_fare.Text)})
Try
sqlCmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("I could not do that because " & ex.Message)
End Try
End Using
Then when you want to display the From and To with the text "To" inbetween, you just retrieve the [From] and [To] values from the database and concatenate them in a string with " To " inbetween, e.g.
Dim journey As String = String.Format("{0} To {1}", fromLocation, toLocation)