As part of a school project, I'm creating a program that simulates a student handing in a test, a student checking his grade, and then a student returning a test. I feel as if I've got the program down, but now VisualBasic is throwing me a InvalidOperationException for my foreach loop because the collection was modified. My program IS working as far as I can tell (I have a debug line that operates as intended).
I'm relatively new at C#, so if I'm off the base anywhere, please let me know. The code is as follows.
First, the error
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: Collection was modified; enumeration operation may not execute.
The code (if anyone needs my object class, just say so)
//Stack and Queue calls
Queue submittedTest = new Queue();
Stack outForChecking = new Stack();
private void btnSubmitTest_Click(object sender, EventArgs e)
{
//generates a random test score
Random rdm = new Random();
int testScore = rdm.Next(0, 100);
string score = testScore.ToString();
//assigns user input to a variable
string name = txtName.Text;
//Generate a new test that passes in
Test tests = new Test(name, score);
//shows the user the name they just enetered
label3.Text = String.Format("{0}", name);
//adds submitted test to the queue, then displays that test in a list box
submittedTest.Enqueue(tests);
listSubTests.Items.Add(new Test(name, score));
//Clears input box for next user input
txtName.Clear();
}
private void btnFindTest_Click(object sender, EventArgs e)
{
string tempName = txtName.Text;
foreach (Test tests in submittedTest)
{
if(tests.Name == tempName)
{
//Remove correct test from submittedTest que
submittedTest.Dequeue();
//Add correct test to a new array, outForChecking
outForChecking.Push(tests);
//Tester to validate how many items are left in the submittedTest que
Console.WriteLine("{0}", submittedTest.Count);
}
}
}