2016-09-28 77 views
0
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区块不会停止那种异常吗?由于'System.ArgumentOutOfRangeException'

+2

您应该递增'currentIndex'的值,然后检查它是否小于'ctx.Employees.Count()' – Nasreddine

回答

1

执行currentIndex++;

Employee empl = ctx.Employees.ToList().ElementAt(currentIndex);

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(); 
     } 
    } 

} 
相关问题