Maestro Vladimir
Maestro Vladimir

Reputation: 1196

Add Text and Value in ComboBox VB6

I learn visual basic, but I am confused when add value and text in combo box.

This is my sample data:

Kode(value) | Name (Text)
DTR001 | Director
SVS005 | Supervisor
MKR001 | Marketing 

In HTML code like this:

<select name="mydata">
    <option value="DTR001">Director</option>
    <option value="SVS005">Supervisor</option>
    <option value="MKR001">Marketing </option>
</select>

How to save add value in combo box VB 6, this is my shortcode:

Private Sub Form_Load()
     cmb1.AddItem "test1"
     cmb1.AddItem "test2"
     cmb1.AddItem "test3"
End Sub
    
Private Sub cmb_jabatan_Click()
    
End Sub

Upvotes: 1

Views: 28199

Answers (1)

Alex K.
Alex K.

Reputation: 175766

You need to maintain an array of the value strings, you can access the correct element by looking at the zero based list index of the combobox item.

Private mValues() As String

Private Sub Form_Load()
    ReDim mValues(2)
    mValues(0) = "DTR001"  '// ListIndex 0
    mValues(1) = "SVS005"
    mValues(2) = "MKR001"

    cmb1.AddItem "Director"
    cmb1.AddItem "Supervisor"
    cmb1.AddItem "Marketing"
End Sub

Private Sub cmb1_Click()
    MsgBox cmb1.List(cmb1.ListIndex) & "/" & mValues(cmb1.ListIndex)
End Sub

You can only directly associate an arbitrary integer with a combobox item using ItemData

.AddItem "Foo"
.ItemData(.NewIndex) = 42

And retrieve with

cmb1.ItemData(listIndex)

You could use this instead of .ListIndex to link to the array if needed.

Upvotes: 4

Related Questions