ruby student
ruby student

Reputation: 1129

Get the selected item in a listbox

I am new to VB6. I need to get the selected item in a listbox to set its content to be the text of a textbox when I press the Modify button.

Private Sub Modify_Click()
    List2.List(0) = Text3.Text
End Sub

I need to change index 0 for the selected item from the listbox.

In VB.Net, I used the following statement but, in VB6, I don't know how to do it.

val=ListBox2.SelectedItem.Value 

Upvotes: 3

Views: 36430

Answers (1)

Bond
Bond

Reputation: 16321

ListIndex returns the zero-based index of the selected item or -1 if no item is selected. Use it in conjunction with the List() collection to retrieve the selected item.

For example:

If List2.ListIndex < 0 Then
    Debug.Print "No item selected."
Else
    Debug.Print "Selected text = " & List2.List(List2.ListIndex)
End If

Or, you can just use the Text property. If no item is selected, Text will return an empty string.

Debug.Print List2.Text

If your ListBox allows for multiple selections, you'll need to loop through the items and use the Selected() function to determine which are selected:

For i = 0 To List2.ListCount - 1
    If List2.Selected(i) Then Debug.Print List2.List(i)
Next

So, to answer your question, to change the text of the selected item to that of your textbox, use the following:

If List2.ListIndex >= 0 Then
    List2.List(List2.ListIndex) = Text3.Text
End If

Upvotes: 5

Related Questions