Collections and Enumerator Help, please!

Feb 9 2007 9:56 AM
Hi I'm getting very confused over why I'm getting an InvalidOperationException.

In a nutshell, I'm writing a program for windows mobile 2003 which holds comments, for field surveys etc. on the comment page you have a ComboBox which holds a list of items. you select any given item and add your comment to that item, then you can click save and it saves the whole comment.. separate class to hold comment ID and two comment fields which go with that ID...

once the comment is saved it is added to a list which holds a list of Comments i.e. List...

now when you select an ID from the given ComboBox i enumerate through the List to see if there is a saved comment relevant to that ID and then it displays it. and for this i'm using this code.

private void itemBox2_TextChanged(object sender, EventArgs e)
{

String currentItem = Convert.ToString(itemBox2.Text);

if (RailAudit.comments.Count > 0)
{
Boolean hasComment = false;
foreach (Comment comment in RailAudit.comments)
{
String currentCommentNumber = comment.getQuestionNumner();
if (currentCommentNumber == currentItem)
{
this.actTakenETB2.Text = comment.getActionTaken();
this.comActETB2.Text = comment.getActionRequired();
hasComment = true;
removebtn.Visible = true;
}
else if(!hasComment)
{
removebtn.Visible = false;
}
}
}
}

This works perfectly, no problems at all.

If an item is found, then it displays it, as well as a remove button. now then i click the remove button, the program should enumerate through the list again find if that given ID is in the list (which it would be otherwise you wouldn't be able to click remove) and removes it. using the following code:

void removebtn_Click(object sender, EventArgs e)
{
//if (RailAudit.comments.Count > 0)
//{
// foreach (Comment comment in RailAudit.comments)
// {
// String currentCommentNumber = comment.getQuestionNumner();
// if (currentCommentNumber == Convert.ToString(itemBox2.Text))
// {
// RailAudit.comments.Remove(comment);
// }
// }
//}

IEnumerator enumerator = RailAudit.comments.GetEnumerator();
while (enumerator.MoveNext())
{
Comment currentComment = (Comment)enumerator.Current;
if (currentComment.getQuestionNumner() == Convert.ToString(itemBox2.Text))
{
RailAudit.comments.Remove(currentComment);
}
}
RailAudit.savedItems.removeItem(Convert.ToString(itemBox2.Text));
this.label2.Text = RailAudit.savedItems.displaySavedItems(2);
removebtn.Visible = false;
}

As you can see i've tried a couple of ways, one using the foreach function and the other using the IEnumerator interface. they both should do pretty much exactly the same thing (i think) but with that second peace of code it get an InvalidOperationException. and VisualStudios 2005 points to the funtion:
while (enumerator.MoveNext())

please can someone shed some light on the situation, i've tried to explain it as best i can. cheers

Answers (2)