如何解决索引超出范围错误?

Joh*_*ohn 4 c#

我有一个包含studentList学生的组合框.当我选择学生时,它应该填写学生姓名的文本字段.每当从组合框中选择学生时,我都会收到以下错误

ArgumentOutOfRangeException was unhandled
Index was out of range. Must be non-negative and less than the size of the collection.
Run Code Online (Sandbox Code Playgroud)

我认为问题可能在我的循环中,但我无法找到如何解决错误,任何帮助将不胜感激

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*sai 7

它抛出错误的原因是在休息之后,我会增加.如果我是列表中的最后一项,它现在已经超出界限了.如果不是,它现在指向下一个项目.

简单的解决方案是移动将错误抛到休息之上的线;

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,请考虑使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


The*_*der 6

发生错误是因为for循环中的最后一个循环i增加1:

i++
Run Code Online (Sandbox Code Playgroud)

然后在表达式中求值为false:

i < Main.studentList.Count
Run Code Online (Sandbox Code Playgroud)

因此,当您到达发生错误的行I等于 Main.studentList.Count,因此发生索引超出范围错误.

如果要访问列表的最后一个元素,可以执行以下操作:

Main.studentList[Main.studentList.Count - 1].StudentName
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要评估每个循环上的语句,只需将其移到for循环中:

for (int 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这还具有将变量保持在i局部范围内的优点.