用多个结果填充多个组合框

Fill multiple combo boxes with multiple results

我有五个组合框,需要填充与每个组合框中插入的文本相关的项目。

如何在 DataTable 中重复使用相同的函数来填充具有不同结果的多个组合框?

Private Sub Search()

    Dim adp As SqlDataAdapter = New SqlDataAdapter("select stage from sample where stage like '%" + ComboBox1.Text + "%'", connection)

    Dim table As New DataTable
    adp.Fill(table)

    ComboBox1.DataSource = New BindingSource(table, Nothing)
    ComboBox1.DisplayMember = "stage"
End Sub

Private Sub ComboBox1_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles ComboBox1.PreviewKeyDown
        If e.KeyCode = Keys.Tab Then
            Search()
        End If
    End Sub

创建一个像这样工作的函数:

Public Sub BindComboBox(ByRef cboBox As ComboBox, ByVal sSQL As String, ByVal sFieldNameOfReturnValue As String, ByVal sFieldNameOfDisplayText As String)
    Try
        Dim adp As SqlDataAdapter = New SqlDataAdapter(sSQL, connection)
        Dim dtAllData As New DataTable
        adp.Fill(dtAllData)

        Dim xBindingContext As New BindingContext
        With cboBox
            .BindingContext = xBindingContext
            .DataSource = dtAllData

            .ValueMember = sFieldNameOfReturnValue.ToUpper
            .DisplayMember = sFieldNameOfDisplayText.ToUpper
        End With
    Catch Exp As Exception
        'Handle exceptions here
    End Try
End Sub

那么你可以这样调用这个函数:

Call BindComboBox(ComboBox1, "select stage from sample where stage like '%" + ComboBox1.Text + "%'", "stage", "stage")
Call BindComboBox(cboCompanies, "SELECT CompanyID, CompanyName, FROM Companies", "CompanyID", "CompanyName")