loop through listbox values

  • Thread starter Thread starter yue
  • Start date Start date
ListBox items accept objects of any type as elements. Find where the
elements are being added, and use that class in the foreach. For instance,
if you do this

listBox1.Items.Add(new MyCustomClass("Hi", 3, true));

then you would do this to get the values

foreach (MyCustomClass item in listBox1.Items) {
}

Chris
 
Chris,
This is good if you use the add method of the listbox.
I set the listbox Datasource on a filtered DataTable.
This is why i need to loop through the listbox and get the
elements.

Is there no easy way to do this? This is so frustrating to
me...

yue
 
In this case, you ought to loop through the datasource instead of the list
box's collection. For a DataTable, this is

foreach (DataRow row in dataTable1.Rows) {}

It ought to be similar for a DataView.

Chris
 
How do I loop through listbox items?

Items is a property of a listBox containing a collection. If you follow
the links from ListBox Class to ListBox Members to Items (inherited from
ListControl) to ListControl.Items Property you will find one example of
how to iterate through the list.

In addition, follow through from CollectionBaseClass, CollectionBase
Members to GetEnumerator which describes also MoveNext, Current and
Reset.

So essentially you have choices of for, foreach and GetEnumerator
approaches to do what you want to do.

Gerald
 
Back
Top