How can I loop through a listbox

aliweb
07-27-2005, 10:38 AM
This is such a simple question. How do I loop through all the items in a listbox in VB.Net.

jayceepoo
07-27-2005, 10:48 AM
This should do it:

Dim i As Integer

For i = 0 To ListBox.Items.Count - 1
MessageBox.Show(ListBox.Items(i))
Next

vbtricks
07-31-2005, 08:43 AM
Or more beautiful:

For i As Integer = 0 To ListBox.Items.Count - 1
MessageBox.Show(ListBox.Items(i))
Next

(works with .net framework 1.1 and above)

Stefan

Iceplug
07-31-2005, 09:11 PM
Even simpler could depend on what you want to do.
The below does an Enumerated walk through the ListBox's .Items collection (you can do For Each with any collection), which is handy if you don't need the index and don't plan on executing a premature exit.

Dim S As datatypethatsinthelistbox, say String
For Each S In LBx.Items
MessageBox.Show(S)
Next
However, if you merely want to find an element, you can do
.IndexOf or .Contains
For removing
.Remove
Additionally, the listbox control supports other fancy functions that you might like to execute a few times.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum