Search code examples
vb.netdatatablecomboboxbindingsource

Fill multiple combo boxes with multiple results


I have five combo boxes that need to populate items related to the text inserted in each of them.

How can I reuse the same function to fill multiple combo boxes with different results in 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

Solution

  • Create a function that works something like this:

    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
    

    Then you would call this function like this:

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