2016-09-28 53 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(); 
     } 
    } 

} 
相關問題