首页 > 解决方案 > 如何从另一个表单 vb.net 获取 SelectedIndex

问题描述

我正在尝试同时添加员工和他们的工作。我有一个 ID 表,我试图将两条记录都插入其中。我有一个 FIND 按钮,可以在另一个填充了 Jobs 的表单上打开一个组合框。一旦做出选择,它将填充第一个表单上的 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

标签: vb.netcomboboxselectedindex

解决方案


您应该对此代码进行大量重构。从这个开始,它将帮助您到达您想去的地方:

  • 放弃过时的匈牙利符号。
  • 让您的工作选择器表单公开两个属性:SelectedJobName 和 SelectedJobID
  • 给作业选择器表单一个更有意义的名称,因为它不会只返回作业名称。例如JobPickerForm
  • 实例化作业选择器表单的一个实例:Using f As New frmSelectJobName
  • 从属性中获取选定的值:例如selectedJobID = f.SelectedJobID
  • 在验证和连接检查之前询问用户是否真的要添加员工。
  • 您正在使用 SQL Server。使用 SqlClient 命名空间中的对象而不是 OleDb。
  • 将数据库中的员工 ID 字段声明为IDENTITY字段,因此您不必使用 hacky MAX(ID) + 1
  • 使用存储过程进行查询。当前方法对 SQL 注入开放。虽然您仍然可以使用内联 SQL,但我发现 SP 更适合我自己。
  • 返回SCOPE_IDENTITY添加到员工表中的员工的 。这为您提供了添加的员工的主键值。
  • 使用构造实例化所有 SqlClient 对象Using。声明并在本地打开您的 SqlConnection 到子/函数,而不是其他地方。
  • 无论 Form_Load() 中的内容是什么,都将其放入单独的 Sub 中,然后调用该 sub。你正在传递一个sender, 并且从你的代码片段中,我不知道这段代码在什么事件中。

执行这些操作,如果您的问题仍然存在,请使用重构的代码更新您的原始帖子,我将通过编辑我的答案继续提供帮助。

这是重构 JobPickerForm 属性的示例。

Public Class JobPickerForm

    Public ReadOnly Property SelectedJobID As Integer = 0
    Public ReadOnly Property SelectedJobName As String = String.Empty


    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        ' Whatever code you have that loads the JobsListBox.....

    End Sub

    Private Sub SelectButtonClickEvent(sender As Object, e As EventArgs) Handles SelectButton.Click

        _SelectedJobID = CInt(JobsListBox.ValueMember)
        _SelectedJobName = JobsListBox.DisplayMember.ToString

    End Sub

End Class

以下是使用新 JobPickerForm 的示例:

Dim selectedJobName As String = String.Empty
Dim selectedJobID As Integer = 0

Using f As New JobPickerForm

    f.ShowDialog()

    selectedJobID = f.SelectedJobID
    selectedJobName = f.SelectedJobName

End Using

推荐阅读