Insert string into different tables based on combobox selection - vb.net

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'

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.

VB.Net/Access SQL insertion sub query issue

I am making a form that can be filled in and will execute a insertion query with a button. I do not know how to reference another table within this block of code. I am trying to insert the Name, Phone Number, and Email within the form along with the corresponding Distributor ID. The only way to get the Distributor ID is to reference the Distributor table. Anyone have any ideas? Thanks!
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
provider = 0
dataFile = 0
provider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
dataFile = "XXXXXXX.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'*THIS IS THE PROBLEM AREA*'
Dim str As String
str = "INSERT INTO [Distributor Contact] ([Name], [Phone Number], [Email], [Distributor ID]) VALUES(?,?,?,?) WHERE [Distributor ID] IN (SELECT DISTINCT [Distributor ID] FROM [Distributor] WHERE [Distributor Name]= '" & ComboBox_Dist.SelectedItem.ToString() & "'))"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("Name", CType(TextBox2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Phone Number", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox4.Text, String)))
Me.Refresh()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
MsgBox("Contact Added")
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
'RE-POPULATE COMBOBOX
ComboBox_Dist.Items.Clear()
Dim connString1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= XXXXXXXXX.mdb"
Dim con As OleDbConnection = New OleDbConnection(connString1)
Dim adapter As OleDbDataAdapter
Dim cmd2 As OleDbCommand
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT * FROM [Distributor Contact];"
cmd2 = New OleDbCommand(sql, con)
Try
con.Open()
adapter = New OleDbDataAdapter(cmd2)
adapter.Fill(dt)
'Add Items To ComboBox
For Each row In dt.Rows
ComboBox_Dist.Items.Add(row(1))
Next
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Add the ComboBox_Dist as a parameter and then use a Select instead of Values for your insertion query. The select allows you to reference the Distributor table.
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("DistributorName", ComboBox_Dist.SelectedItem.ToString()))
str = "INSERT INTO [Distributor Contact] ([Name], [Phone Number], [Email], [Distributor ID]) "
str += "SELECT ?,?,?, [Distributor].[DistributorID] "
str += "FROM [Distributor] WHERE [Distributor].[Distributor Name] = ?"
Here is the final working code for anyone in the future.
provider = 0
dataFile = 0
provider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
dataFile = "XXXXXXXX.mdb"
connString = provider & dataFile
Dim str As String
str = "INSERT INTO [Distributor Contact] ([Contact Name], [Phone Number], [Email], [Distributor ID])"
str += "SELECT ?,?,?,[Distributor].[Distributor ID]"
str += "FROM [Distributor] WHERE [Distributor].[Distributor Name] = ?"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("Contact Name", CType(TextBox2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Phone Number", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Distributor Name", ComboBox_Dist.SelectedItem.ToString()))
Me.Refresh()

Procedure only updates the first value

I have this SQL procedure for updating records given a #StepId value.
I got the values from a hidden field as an array and I loop them.
The problem is that the procedure only updates the first value.
The loop happen but do not update more than 1 value.
my array contains something like {1000,2000,3000,}
my parameters are
#StepId (int)
#DateCalculationRule (char)
#Result (int)
Private Sub buttonCalculateDatesClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonCalculateDates.Click
Dim mySteps As String
Dim myRule As String
Dim ok As Integer = 1
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("cnnstring").ConnectionString
Dim conn As SqlConnection = New SqlConnection(connectionString)
Dim cmd As New SqlCommand("SaveStepDeadlineRule", conn)
conn.Open()
conn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
myRule = HiddRule.Value
mySteps = HiddStepIDs.Value
'Separate string by comas
Dim parts As String() = mySteps.Split(New Char() {","c})
Dim part As String
For Each part In parts
cmd.Parameters.Add(New SqlParameter("#StepId", part))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", myRule))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next
conn.Close()
End Sub
You will need to clear down your parameters each time you loop:
cmd.Parameters.Clear
This is how it would be used:
For Each part In parts
cmd.Parameters.Clear()
cmd.Parameters.Add(New SqlParameter("#StepId", part))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", myRule))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next
You could create the parameters outside the loop since they don't change and then just assign the value each time you loop:
cmd.Parameters.Add(New SqlParameter("#StepId", 0))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", ""))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
For Each part In parts
cmd.Parameters("#StepId").Value = part
cmd.Parameters("#DateCalculationRule").Value = myRule
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next

Save to Oracle joined table using ID

I save data from my form to Oracle DB table. Now I need to store data in joined table If my datagridview rows are not empty too, but this is where I got stucked. Joined table has ID_Table1_FK. Here is what I tried:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using con As OracleConnection = New OracleConnection("Data Source=MyDB;User Id=Lucky;Password=MyPassword;")
con.Open()
Using cmd As OracleCommand = New OracleCommand()
cmd.CommandText = "INSERT INTO Table1(ID_Table1_PK, E_NAME, E_SURNAME, DESCRIPTION, ENTRY_DATE)
VALUES(MyTable_seq.nextval,: ID,: Name,: Surname,: Desc,: Entry)"
cmd.Connection = con
cmd.Parameters.Add(New OracleParameter("ID", TxtName.Text))
cmd.Parameters.Add(New OracleParameter("Surname", TxtSurname.Text)
cmd.Parameters.Add(New OracleParameter("Desc", TxtDesc.Text))
cmd.Parameters.Add(New OracleParameter("Entry", DtpEntry.Value.ToShortTimeString))
cmd.ExecuteNonQuery()
End Using
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value = Nothing Then
Else
Using cmd1 As New OracleCommand()
cmd1.CommandText = "INSERT INTO Table_Join (ID_Table1, ID_Table_Join, ADDRESS, STATE)
VALUES(ID_Table1,: MyTable_seq.nextval,: address,: state)"
cmd1.Parameters.Add(New OracleParameter("ID_Table1", "WHAT SHOULD GO HERE??"))
cmd1.Parameters.Add(New OracleParameter("address", row.Cells(0).Value))
cmd1.Parameters.Add(New OracleParameter("state", row.Cells(1).Value))
cmd1.ExecuteNonQuery()
End Using
End If
End Using
End Sub
So basically I need any advice on how to pass same ID value to another (joined) table ?
P.S.: "MyTable_seq.nextval" is triggering automatic sequence number of records in DB.

How do you stop and reset a form before it submits data to a database

I am making a login page and I have done the registration form, however, I need to validate the username. I have done the validating part, however, I can't seem to get it to not submit the data and reset the username box. This is the code
Imports System.Data.OleDb
Public Class Register
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub rB_Click(sender As Object, e As EventArgs) Handles rB.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Harry\Documents\Visual Studio 2015/users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim usf As OleDbCommand = New OleDbCommand("SELECT * FROM [users] WHERE [username] = '" & uT.Text, myConnection)
Dim userFound As Boolean = True
If userFound = True Then
MsgBox("Username already found; Please choose another")
Dim frm = New Register
frm.Show()
Me.Close()
End If
Dim str As String
str = "insert into users ([username], [password], [Firstname], [LastName]) values (?, ?, ?, ?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(uT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(pT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("FirstName", CType(fnT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("LastName", CType(lnT.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
uT.Clear()
pT.Clear()
fnT.Clear()
lnT.Clear()
Me.Hide()
Form2.Show()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
First, please post your code instead of including an image as it's hard to reference back to when describing problems found.
That being said. You have a boolean UserFound that you are declaring and setting to True and then immediately checking to see if it's true. Of course it's going to be true, you just set it.
Also, I see nowhere in that image where you're even passing the query to get results back. (ie, executeReader, executeScalar)
Typically you can query the database and then check to see if any rows were returned or use executeScalar against a single column to see if a value was returned.