Outputting all ListBox values using a while loop

  • Thread starter Thread starter David Hubball
  • Start date Start date
D

David Hubball

Hi

Does anyone know how to do a small program to return the values in a
ListBox without it crashing.

I've tried the code below but it crashes when indexing down my ListBox
called listboxFilesToBackup.

int index = 0;
listboxFilesToBackup.SelectedIndex = index;


while (listboxFilesToBackup.SelectedItem.ToString()!="")
{
MessageBox.Show
(listboxFilesToBackup.SelectedItem.ToString());
index++;
listboxFilesToBackup.SelectedIndex = index;

}

Much Appreciate if anyone can help as I'm very new to c#. I've got
this working once by using Try Catch but just wondered if there is a
cleaner way of getting the values that I've missed.

Kind Regards
David
 
Hi

I think I've working it out now. My solution to scanning down a
listbox uses the listbox.item.count propery :-

int index = 0;
listboxFilesToBackup.SelectedIndex = index;
int intlistboxCount=listboxFilesToBackup.Items.Count;

while (index++<intlistboxCount)
{
MessageBox.Show
(listboxFilesToBackup.SelectedItem.ToString());
listboxFilesToBackup.SelectedItem =
index;
}

But if anyone has an even neater solution it would be appreciated.

Cheers
David
 
But if anyone has an even neater solution it would be appreciated.

I tend to use 'foreach' e.g.
foreach (object current in listboxFilesToBackup.SelectedItems)
....

It stops me from falling past the last item with an Index that is too big.
You can use object or string in the foreach statement depending on what's
in the ListBox and what you want to do with it. In some of my apps the
ListItems are instances of a class so 'object' can be cast to the
appropriate type.
 
Back
Top