Search code examples
vb.netwinformscombobox

Indicate combobox values with a specific ids?


I made a Sub that will populate my combobox with loan descriptions. I want to get the loancode of the loandescription on selectedindexchanged without querying again the database. Is this possible? Or should I query the database to get the indicated loancode?

Private Sub LoanProducts()
    Using cmd As New SqlClient.SqlCommand("SELECT loancode,loandescription FROM LoanProducts", gSQlConn)
        Dim dt As New DataTable
        Dim da As New SqlClient.SqlDataAdapter
        dt.Clear()
        da.SelectCommand = cmd
        da.Fill(dt)
        For Each row As DataRow In dt.Rows
            CmbLoanAvail.Items.Add(row("loandescription"))
        Next row
    End Using
End Sub

Expected output:

Everytime the combobox index changed, the loancode of the selected loandescription will be displayed to a textbox.


Solution

  • Set DataTable to combobox .DataSource property and populate .ValueMember and .DisplayMember properties with corresponding column names.

    Private Sub LoanProducts()
        Dim query As String = "SELECT loancode, loandescription FROM LoanProducts"
        Using command As New SqlCommand(query, gSQlConn)
            Dim data As New DataTable
            Dim adapter As New SqlClient.SqlDataAdapter With
            {
                .SelectCommand = cmd
            }
    
            adapter.Fill(data)
    
            CmbLoanAvail.ValueMember = "loancode"
            CmbLoanAvail.DisplayMember = "loandescription"
            CmbLoanAvail.DataSource = data
        End Using
    End Sub
    

    You can use SelectionChangeCommitted event to execute some action when user made a selection

    Private Sub comboBox1_SelectionChangeCommitted(
        ByVal sender As Object, ByVal e As EventArgs) Handles comboBox1.SelectionChangeCommitted
    
        Dim combobox As ComboBox = DirectCast(sender, ComboBox)
    
        Dim selectedCode As String = combobox.SelectedValue.ToString()  // returns 'loancode'
    End Sub