tags:

views:

84

answers:

1

Hi,

I have a listbox with items, and when I press a button I would like to go to the next item. I'm having a horrible brain fart and have been for quite some time.

for x = 0 to listbox1.items.count - 1
     label1.text = listbox1.items.item(x)
     x += 1
next

Probably a dumb mistake on my part :( Thanks!

+1  A: 

Put the code inside the loop into the Click event handler.

Private listItemIndex As Integer = 0

Private Sub Button_Click(sender As Object, e As EventArgs)
    If listItemIndex < ListBox1.Items.Length Then
        Label1.Text = ListBox1.Items(listItemIndex).ToString()
        listItemIndex += 1
    End If
End Sub

And, should you ever need to loop over all items as in your original code, always prefer the For Each loop to the indexed loop. It is more concise and more direct and hence (arguably) more idiomatic.

For Each item In ListBox1.Items
    Label1.Text = item.ToString()
Next

/EDIT: Pay attention to enable Option Strict everywhere in your project unless there's a compelling reason not to. This makes the compiler recognize a lot more potential problems for you. It also means that the above code needs an explicit cast (or call to ToString) since ListBox.Items returns Objects.

Konrad Rudolph
+1 After re-reading I think this may be what the OP is after.
Andrew Hare