The reason she throws a mistake is that after the break, I get an increment. If I was the last item on the list, it is now out of scope. If it is not, now it points to the next element.
A simple solution would be to move the line that throws an error above break;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i;
for (i = 0; i < Main.studentList.Count; i++)
{
if (comboBox1.SelectedItem == Main.studentList[i].StudentName + " " + Main.studentList[i].StudentId)
{
txtName.Text = Main.studentList[i].StudentName;
break;
}
}
}
foreach. foreach. .
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var student in Main.studentList)
{
if (comboBox1.SelectedItem == student.StudentName + " " + student.StudentId)
{
txtName.Text = student.StudentName;
break;
}
}
}