terrydiederich2
1/10/2019 - 3:11 PM

ComboBox with Key and Value

Use a Dictionary to load the combobox

    Dim table As New DataTable
    table = dbEstimateStatuses.GetAllActive()
    Dim comboSource As New Dictionary(Of Integer, String)()
    For Each row As DataRow In table.Rows
        comboSource.Add(row("id"), row("description"))
    Next

    cmbStatus.DataSource = New BindingSource(comboSource, Nothing)
    cmbStatus.DisplayMember = "Value"
    cmbStatus.ValueMember = "Key"

To retrive a value from the selected item, cast the selected item to a KeyValuePair

    Dim id As Integer = -1
    Dim description As String = ""

    If Not cmbStatus.SelectedItem Is Nothing Then
        id = DirectCast(cmbStatus.SelectedItem, KeyValuePair(Of Integer, String)).Key
        description = DirectCast(cmbStatus.SelectedItem, KeyValuePair(Of Integer, String)).Value
    End If

To set a selected item

    cmbStatus.SelectedValue = 2

or

    cmbStatus.SelectedIndex = cmbStatus.FindStringExact("Pending")