I hava a combo box that contains students from a studentList. When I select a student it should populate a text field of the students name. Whenever a student is selected from the combo box I get the following error
ArgumentOutOfRangeException was unhandled
Index was out of range. Must be non-negative and less than the size of the collection.
I think the problem may be in my loop but I'm having trouble finding out how to fix the error, any help would be appreciated
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)
{
break;
}
}
txtName.Text = Main.studentList[i].StudentName; //where the error occurs
}
public void ChangeStudent_Load(object sender, EventArgs e)
{
//loading combobox from studentList
foreach (var student in Main.studentList)
{
comboBox1.Items.Add(student.StudentName + " " + student.StudentId);
}
}
The reason it's throwing an error is after the break, i gets incremented. If i was the last item in the list, it's now out of bounds. If it wasn't, it's now pointing to the next item.
The simple solution would be to move the line that is throwing the error above the 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;
}
}
}
Also, consider using a foreach loop. Here's the exact same logic with a foreach loop. It makes it a bit more readable.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With