dwb
dwb

Reputation: 483

Using each item in a list box

I am working on a new application and am trying to work with a Listbox. What I am trying to do is run a task with each item in the Listbox one at a time.

Example:

Items in Listbox:

For this example, I would like the program to start at the top at 'Dog', display the result, then go to 'Cat', and so on until there are no more items.

Side note: I would also like it if there was a way to highlight what item it was currently on.

Thanks in advance guys, I am working on learning some of the other features of the ListBox with this new application.

Upvotes: 0

Views: 402

Answers (1)

Chris Fannin
Chris Fannin

Reputation: 1294

The ListBox has some properties you may be interested in.

  • You want to highlight the item. Therefore, you'll need the SelectedIndex
  • Since you want to select it, a standard For loop will be needed.
  • To access the items in the list, you use the Items collection.
  • The Items collection has a Count property.

Here is an example based on what you provided. AnimalList is a ListBox, and ShowNames is a Button:

   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

      AnimalList.Items.AddRange({"Dog", "Cat", "Fish", "Cow"})

   End Sub

   Private Sub ShowNames_Click(sender As Object, e As EventArgs) Handles ShowNames.Click

      For i As Integer = 0 To AnimalList.Items.Count - 1

         AnimalList.SelectedIndex = i
         MessageBox.Show(AnimalList.Items(i).ToString())

      Next

   End Sub

If you set the SelectedIndex, you can also access the SelectedItem property.

When you have a multi-select list, there are also SelectedIndices and SelectedItems properties.

Upvotes: 1

Related Questions