我有一个组合框,其中包含studentList的学生。当我选择一个学生时,它应该填充学生姓名的文本字段。每当学生从组合框中选择我收到以下错误如何解决索引超出范围错误?
ArgumentOutOfRangeException was unhandled
Index was out of range. Must be non-negative and less than the size of the collection.
我觉得问题可能出在我的循环,但我无法找出如何修正这个错误,任何帮助,将不胜感激
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);
}
}
您是否尝试过调试应用程序?在发生错误的行上放置一个断点 - 然后检查“i”的值。 –
您正在循环外使用循环变量('i')。这很少是一个好主意。你认为'我'有什么价值?在循环之后? – MAV