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

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.

Related

Command text was not set for the command object using vb and ms-access

The question:
-Display a message for validation if the user entered existing data (name, staff id, phone number, username and password).
THESE ARE THE CODES
my database works but the msgbox appeared saying the command text wat not set for the command object
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SEM 5\CSC301\ASSESSMENT 3\database.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SEM 5\CSC301\ASSESSMENT 3\database.accdb"
con.Open()
Dim registercmd As OleDbCommand = New OleDbCommand("select * from users where [Librarian Name]='" & txtName.Text & "' or [Staff ID]='" &
txtStaffID.Text & "' or [Phone Number]='" & txtPhone.Text & "' or [Username]='" &
txtUsername.Text & "' or [Password]='" & txtPassword.Text & "'", con)
Dim registerrd As OleDbDataReader = registercmd.ExecuteReader
If (registerrd.Read() = True) Then
Me.Hide()
MessageBox.Show("Account Exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Hide()
Me.Show()
txtName.Clear()
txtStaffID.Clear()
txtPhone.Clear()
txtUsername.Clear()
txtPassword.Clear()
Else
command = "insert into users([Librarian Name],[Staff ID],[Phone Number],[Username],[Password])
Values('" & txtName.Text & "','" & txtStaffID.Text & "','" & txtPhone.Text & "','" & txtUsername.Text & "','" & txtPassword.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("ID", CType(txtName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Librarian Name", CType(txtStaffID.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Staff ID", CType(txtPhone.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Phone Number", CType(txtUsername.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Username", CType(txtPassword.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Password", CType(txtPassword.Text, String)))
MsgBox("Account Created")
Me.Hide()
Login.ShowDialog()
End If
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtName.Clear()
txtStaffID.Clear()
txtPhone.Clear()
txtUsername.Clear()
txtPassword.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Your code starts out with several undeclared variables. The connection string variable can be a class level variable so it can be used in several methods. Then you open a connection that you don't use until half way down the code. Don't open connections utill directly before the .Execute.... I read a very good analogy here on Stack Overflow. Connections are like refrigerator doors. Open only when you must. Get out or put in what you need to as quickly as possible. Then close as soon as possible. You can pass the connection string directly to the constructor of the connection.
Database objects need to be disposed. Using...End Using blocks handle this for us even if there is an error. I had to guess at the data type of the parameters. Please check your database for the correct type and correct the code accordingly.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SEM 5\CSC301\ASSESSMENT 3\database.accdb"
Private Sub OpCode()
Dim exists As Boolean
Using con As New OleDbConnection(ConStr),
registercmd As OleDbCommand = New OleDbCommand("select * from users where
[Librarian Name]= #Name or
[Staff ID]= #StaffID or
[Phone Number]= #Phone or
[Username]= #User or
[Password]= #PWord;", con)
With registercmd.Parameters
.Add("#Name", OleDbType.VarWChar).Value = txtName.Text
.Add("#StaffID", OleDbType.VarWChar).Value = txtStaffID.Text 'Often an ID is a numeric type. Check your database.
.Add("#Phone", OleDbType.VarChar).Value = txtPhone.Text
.Add("#User", OleDbType.VarWChar).Value = txtUsername.Text
.Add("#PWord", OleDbType.VarWChar).Value = txtPassword.Text
End With
con.Open()
Using registered = registercmd.ExecuteReader
If registered.HasRows Then
exists = True
End If
End Using
End Using
If exists Then
MessageBox.Show("Account Exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Using con As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand("insert into users([Librarian Name],[Staff ID],[Phone Number],[Username],[Password])
Values(#Name, #StaffID, #Phone, #UserName, #PWord);", con)
With cmd.Parameters
.Add("#Name", OleDbType.VarWChar).Value = txtName.Text
.Add("#StaffID", OleDbType.VarWChar).Value = txtStaffID.Text
.Add("#Phone", OleDbType.VarChar).Value = txtPhone.Text
.Add("#UserName", OleDbType.VarWChar).Value = txtUsername.Text
.Add("#PWord", OleDbType.VarWChar).Value = txtPassword.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
MsgBox("Account Created")
Hide()
Login.ShowDialog()
End If
txtName.Clear()
txtStaffID.Clear()
txtPhone.Clear()
txtUsername.Clear()
txtPassword.Clear()
End Sub
Another bad problem that I see. Your appear to be storing passwords as plain text. All passwords should be salted and encrypted.

"exception has been thrown by the target of an invocation. in vs 2010

hi When i try to save data to access 2007 database i got error like "exception has been thrown by the target of an invocation" i am making project to take weight from scale and save it to database please help me to solve error.
Try
Dim PRO As String
Dim CONNSTRING As String
Dim COMMAND As String
Dim MYCONNECTION As OleDbConnection = New OleDbConnection
PRO = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\weight.accdb;Persist Security Info=True;Jet OLEDB:Database Password=weight"
CONNSTRING = PRO
MYCONNECTION.ConnectionString = CONNSTRING
MYCONNECTION.Open()
COMMAND = "insert into entry ([weight1],[date1],[time1],[weight2],[date2],[time2],[netweight],[vehicleno],[name],[contactno],[productname],[charge],[paymentstatus]) values ('" & weight1.Text & "','" & date1.Text & "','" & time1.Text & "','" & weight2.Text & "','" & date2.Text & "','" & time2.Text & "','" & netweight.Text & "','" & vehicleno.Text & "','" & custname.Text & "','" & contact.Text & "','" & Product.Text & "','" & charge.Text & "','" & status.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(COMMAND, MYCONNECTION)
cmd.Parameters.Add(New OleDbParameter("weight1", CType(weight1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("date1", CType(date1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("time1", CType(time1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("weight2", CType(weight2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("date2", CType(date2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("time2", CType(time2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("netweight", CType(netweight.Text, String)))
cmd.Parameters.Add(New OleDbParameter("vehicleno", CType(vehicleno.Text, String)))
cmd.Parameters.Add(New OleDbParameter("name", CType(custname.Text, String)))
cmd.Parameters.Add(New OleDbParameter("contactno", CType(contact.Text, String)))
cmd.Parameters.Add(New OleDbParameter("productname", CType(Product.Text, String)))
cmd.Parameters.Add(New OleDbParameter("charge", CType(charge.Text, String)))
cmd.Parameters.Add(New OleDbParameter("paymentstatus", CType(status.Text, String)))
MsgBox("Saved")
cmd.ExecuteNonQuery()
cmd.Dispose()
MYCONNECTION.Close()
weight1.Clear()
date1.Text = ""
time1.Text = ""
weight2.Clear()
date2.Text = ""
time2.Text = ""
netweight.Clear()
vehicleno.Text = ""
custname.Text = ""
contact.Text = ""
Product.Text = ""
charge.Clear()
status.Text = ""
weighttype.Focus()
Call ticket()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Write your SQL code like this:
COMMAND = "insert into entry ([weight1]) values (#weight1)"
and then add the parameters like this:
cmd.Parameters.Add("#weight1", OleDbType.VarChar, 50).Value = weight1.Text
Provide a parameter placeholder in the SQL and then use that as the name of the parameter when you add it. Specify the data type as well and, for variable-width types, the size as well. Set the Value or the parameter you just added.
As you're using the ACE OLE DB provider, the parameter names will actually be ignored, but you should use them for your the clarity of your code. You must ensure that parameters are added in the same order they appear in the SQL code.

How to close the sqldatareader within Using statement?

I'd like to use this code to verify if duplication occurs or not before saving the data to the database. How am I supposed to close the sqldatareader? (As what the error shows me)
con.ConnectionString = "Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True"
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()
The error are referring to is because you must complete the execution of the data reader before you try to execute another command on the same connection.
Additionally there are some issues with your code:
It is strongly recommended you use and then dispose of SqlConnections as you use them, do not try to reuse these globally in your application. The ado.net SQL Server client library will handle connection pooling for you by default.
You need to use parameters with your insert just like you did on your select.
Do not to use AddWithValue when adding your parameters, instead use the constructor and also specify the sql data type. If RollNo is a number (like integer) then you should pass the value as an integer to your parameter. I assumed it was a string stored in a varchar.
Wrap all types that implement IDisposable in Using statements to ensure resources are always released. (In case any one wants to nitpick, no it is not required for SqlCommand in this case.)
Dim recordExists As Boolean
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("SELECT RollNo FROM Profile WHERE RollNo=#RollNo AND Name=#Name", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
Using reader As SqlDataReader = cmd.ExecuteReader()
recordExists = reader.HasRows
End Using
End Using
End Using
If recordExists Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("INSERT INTO Profile (RollNo, Name) VALUES (#RollNo, #Name)", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
End Using
End Using
End If
if you are using using then not need to close. because it internally close all connection. The code would be like this
using(var con=new Sqlconnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")){
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()}

How do I reference X controls into a FOR loop?

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.

Handling FileNotFound Exception

cn.Open()
Dim query As String
query = "INSERT INTO Documents(AdmissionNumber,FullName,LeavingCertificate,KCPEResultSlip,BirthCertificate,MedicalCertificate,ParentOrGuardianPhoto,ParentGuardianIDFront,ParentGuardianIDBack,AnyOtherDocument) VALUES('" & Tbx1.Text & "','" & Tbx2.Text & "', #LeavingCertificate,#KCPEResultSlip,#BirthCertificate,#MedicalCertificate,#ParentOrGuardianPhoto,#ParentGuardianIDFront,#ParentGuardianIDBack,#AnyOtherDocument)"
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlClient.SqlParameter("#LeavingCertificate", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog1.FileName)
cmd.Parameters.Add(New SqlClient.SqlParameter("#KCPEResultSlip", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog2.FileName)
cmd.Parameters.Add(New SqlClient.SqlParameter("#BirthCertificate", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog3.FileName)
cmd.Parameters.Add(New SqlClient.SqlParameter("#MedicalCertificate", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog4.FileName)
cmd.Parameters.Add(New SqlClient.SqlParameter("#ParentOrGuardianPhoto", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog5.FileName)
cmd.Parameters.Add(New SqlClient.SqlParameter("#ParentGuardianIDFront", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog6.FileName)
cmd.Parameters.Add(New SqlClient.SqlParameter("#ParentGuardianIDBack", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog7.FileName)
cmd.Parameters.Add(New SqlClient.SqlParameter("#AnyOtherDocument", SqlDbType.Image)).Value = IO.File.ReadAllBytes(OpenFileDialog8.FileName)
Reader = cmd.ExecuteReader
MsgBox("Students' Documents Added Successfully to The Regista.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Btn9_Click(sender, e)
End Sub
' Hi comrades. You see this code above? This item called (AnyOtherDocument) is optional. The user can either provide it or Not. But when not provided, am getting an Exception error. How do I handle this?
Just check with File.Exists. If there is no file then set the parameter to DbNull.Value otherwise read the file
Dim exists = File.Exists(OpenFileDialog8.FileName)
.....
cmd.Parameters.Add(New SqlClient.SqlParameter( _
"#AnyOtherDocument", SqlDbType.Image)).Value _
= If(exists, IO.File.ReadAllBytes(OpenFileDialog8.FileName), _
DBNull.Value)
By the way, you are using parameters for all of your image values, why don't you use them also for the two string values? The usefulness of parameters is not tied to the DataType of the value to pass. You use them for every value to avoid Sql Injection and parsing problems
query = "INSERT INTO Documents " & _
"(AdmissionNumber,FullName,LeavingCertificate,KCPEResultSlip," & _
"BirthCertificate,MedicalCertificate,ParentOrGuardianPhoto," & _
"ParentGuardianIDFront,ParentGuardianIDBack,AnyOtherDocument) " & _
"VALUES(#admnum, #fullname, #LeavingCertificate,#KCPEResultSlip, " & _
"#BirthCertificate,#MedicalCertificate,#ParentOrGuardianPhoto," & _
"#ParentGuardianIDFront,#ParentGuardianIDBack,#AnyOtherDocument)"
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add("#admnum", SqlDbType.NVarChar).Value = Tbx1.Text
cmd.Parameters.Add("#fullname", SqlDbType.NVarChar).Value = Tbx2.Text
cmd.Parameters.Add("#LeavingCertificate", SqlDbType.Image).Value = IO.File.ReadAllBytes(OpenFileDialog1.FileName)
.... and so on with all the other parameters ....