Problem with foreach loop

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I don't use the foreach statement often so this problem has cought me off
guard. Here is the code:

foreach (int i in EventDates.Items)
{
DateList += EventDates.Items.ToString();
}

I get an "invalid cast" error! and I can't seem to find the solution.

Thanks, Justin.
 
The cast error occures because the item in EventDates is probably not an int
....

You could write:

foreach( object o in EventDates.Items ) {
if ( o is int ) {
int myInt = o;
DateList += o.ToString();
}
}

PS: Remember that (in your code) that the int i is the item, not an index to
be used like EventDates.Items ...
 
Justin said:
I don't use the foreach statement often so this problem has cought me
off guard. Here is the code:

foreach (int i in EventDates.Items)
{
DateList += EventDates.Items.ToString();
}

I get an "invalid cast" error! and I can't seem to find the solution.

Thanks, Justin.


You don't specify the type of EventDates or DateList, but there is (at least)
one thing wrong:
the type in the foreach ("int i" in your case) should be a member of the collection,
not an index!

either change it to:
for (int i = 0; i<EventDates.Items.Count; i++)
DateList += EventDates.Items.ToString();

or to:
foreach (DateListItem dli in DateList.Items)
DateList += dli.ToString();

(change the types to the appropriate ones, I had to guess)

The "for" version might be a bit faster than "foreach"!


Hans Kesting
 
Back
Top