Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I solve an index out of range error?

Tags:

c#

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);
    }
}
like image 429
John Avatar asked Dec 03 '22 14:12

John


1 Answers

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;
        }
    }
}
like image 64
Paul Tsai Avatar answered Dec 24 '22 09:12

Paul Tsai