我有一個組合框,其中包含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