我正在尝试一次添加员工和他们的工作。我正在尝试将两个记录都插入到一个ID表中。我有一个“查找”按钮,可以在另一个装有乔布斯的表单上打开一个组合框。选择之后,将在第一个表单上填充txtJobName文本框。那用应有的工作名称填充,但是我不能拉SelectedIndex插入到TJobEmployees表中。
'Variables
Dim strSelect As String
Dim strInsert As String
Dim strFirstName As String = ""
Dim strLastName As String = ""
Dim strJob As String = frmSelectJobName.strSelectedJob
Dim intJobID As Integer
Dim cmdSelect As OleDb.OleDbCommand
Dim cmdInsert As OleDb.OleDbCommand
Dim dr As OleDb.OleDbDataReader
Dim intNextHighestRecordID As Integer
Dim intRowsAffected As Integer
Dim result As DialogResult
strFirstName = txtFirstName.Text
strLastName = txtLastName.Text
strJob = txtJobName.Text
intJobID = CInt(frmSelectJobName.lstJobs.SelectedValue)
If Validation() = True Then
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user ...
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
' and close the form/application
Me.Close()
End If
' always ask before adding!!!!
result = MessageBox.Show("Are you sure you want to Add Employee: Job-" & txtJobName.Text & "?", "Confirm Submission", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
' this will figure out which button was selected. Cancel and No does nothing, Yes will allow insert
Select Case result
Case DialogResult.Cancel
MessageBox.Show("Action Canceled")
Case DialogResult.No
MessageBox.Show("Action Canceled")
Case DialogResult.Yes
strSelect = "SELECT MAX(intEmployeeID) + 1 AS intNextHighestRecordID " &
" FROM TEmployees"
' Execute command
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
dr = cmdSelect.ExecuteReader
' Read result( highest ID )
dr.Read()
' Null? (empty table)
If dr.IsDBNull(0) = True Then
' Yes, start numbering at 1
intNextHighestRecordID = 1
Else
' No, get the next highest ID
intNextHighestRecordID = CInt(dr.Item(0))
End If
' add the child record
strInsert = "Insert into TEmployees (intEmployeeID, strFirstName, strLastName)" &
" Values (" & intNextHighestRecordID & ",'" & strFirstName & "'," & "'" & strLastName & "')"
cmdInsert = New OleDb.OleDbCommand(strInsert, m_conAdministrator)
intRowsAffected = cmdInsert.ExecuteNonQuery()
'add the parent record
strInsert = "Insert into TJobEmployees (intJobID, intEmployeeID)" &
" Values (" & intJobID & ",'" & intNextHighestRecordID & "')"
' Insert the record(s)
cmdInsert = New OleDb.OleDbCommand(strInsert, m_conAdministrator)
intRowsAffected = cmdInsert.ExecuteNonQuery()
If intRowsAffected > 0 Then
MessageBox.Show("Job has been added")
Me.Close()
End If
End Select
CloseDatabaseConnection()
Form1_Load(sender, e)
End If
您应该对该代码进行很多重构。从此开始,它将帮助您到达想要去的地方:
Using f As New frmSelectJobName
selectedJobID = f.SelectedJobID
IDENTITY
字段,因此您不必使用hacky MAX(ID) + 1
。SCOPE_IDENTITY
。这为您提供了添加的员工的主键值。Using
构造实例化所有SqlClient对象。声明并在本地向Sub / Function(而不是其他地方)打开SqlConnection。sender
,并且从您的代码段中,我不知道此代码在什么事件中。执行这些操作,如果问题仍然存在,请使用重构的代码更新您的原始帖子,我们将通过编辑答案来继续提供帮助。