Domanda

I have a combobox and a textbox. The combobox is sorted as a list alphabetically and has five items. "APPLE" "BEAR" "CAT" "DOG" "ELK". In the database, they are listed with a weight so

APPLE Weighs 2, BEAR weighs 100, CAT weighs 7, DOG weighs 20 and ELK weighs 30,

I would like to change the combobox to select the right animal based off of the weight i type in on Lost_Focus. So i have

 For i = 0 To 4
    If txtField.Text = Me.cmbAnimal.ItemData(i) Then
        Me.cmbAnimal.ListIndex = i
    End If

    Next i  

However, this is comparing the weight to the animal name. How can i reword this?

È stato utile?

Soluzione

In the sample you have 2 different comboboxes: cmbAnimal and cmbSeqCarrier. Which one are you using?

You have the right idea about using ItemData (assuming it stores the weight of the animal). In the sample below, ItemData property holds the weights. If Text1 is the box where you enter the weight, the sample below should do the task you are asking.

'Load weights with the names to a combobox
Private Sub Form_Load()
    cmbAnimal.AddItem "APPLE"
    cmbAnimal.ItemData(cmbAnimal.NewIndex) = 2
    cmbAnimal.AddItem "BEAR "
    cmbAnimal.ItemData(cmbAnimal.NewIndex) = 100
    cmbAnimal.AddItem "CAT"
    cmbAnimal.ItemData(cmbAnimal.NewIndex) = 7
    cmbAnimal.AddItem "DOG"
    cmbAnimal.ItemData(cmbAnimal.NewIndex) = 20
    cmbAnimal.AddItem "ELK"
    cmbAnimal.ItemData(cmbAnimal.NewIndex) = 30
End Sub

If you have weights loaded into ItemData, then this will work just fine:

Private Sub Text1_LostFocus()
    Dim i As Integer
    For i = 0 To cmbAnimal.ListCount - 1
        ' compare weight entered into text box with weights stored in the combobox
        If Trim(cmbAnimal.ItemData(i)) = Trim(Text1.Text) Then
            cmbAnimal.ListIndex = (i)
            Exit For
        End If
    Next i
End Sub
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top