private void Right_Click(object sender, EventArgs e)
{
using (var ctx = new NORTHWNDEntities())
{
if (currentIndex < ctx.Employees.Count())
{
currentIndex++;
Employee empl = ctx.Employees.ToList().ElementAt(currentIndex);
Id.Text = empl.EmployeeID.ToString();
FirstName.Text = empl.FirstName;
LastName.Text = empl.LastName;
DateOfBirth.Text = empl.BirthDate.Value.ToShortDateString();
}
else
{
Load();
}
}
}
所以我必须遍历这个集合,但是当我到达集合的末尾时,我得到了这个异常。有人能告诉我为什么我的if块不能阻止那种异常吗?感谢
答案 0 :(得分:2)
在数组访问后移动增量。 您遇到异常,因为您正在尝试访问不属于为阵列分配的内存的内存。
private void Right_Click(object sender, EventArgs e)
{
using (var ctx = new NORTHWNDEntities())
{
if (currentIndex < ctx.Employees.Count())
{
Employee empl = ctx.Employees.ToList().ElementAt(currentIndex);
Id.Text = empl.EmployeeID.ToString();
FirstName.Text = empl.FirstName;
LastName.Text = empl.LastName;
DateOfBirth.Text = empl.BirthDate.Value.ToShortDateString();
currentIndex++;
}
else
{
Load();
}
}
}
答案 1 :(得分:1)
执行currentIndex++;
Employee empl = ctx.Employees.ToList().ElementAt(currentIndex);
之后