2016-08-04 88 views
1

我有以下代碼來獲取表格數據,但是出現錯誤,我不知道自己在哪裏出錯。指數超出範圍。必須是非負的,並且小於集合的大小

public List<ModelGetEmployeeList> GetEmployeeList() 
      { 

       List<ModelGetEmployeeList> empList = new List<ModelGetEmployeeList>(); 
       DataTable dt = new DataTable(); 

       string q = "select uid,fname,lname from nworksuser;"; 
       MySqlCommand cmd = new MySqlCommand(q,conn); 
       MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); ; 
       conn.Open(); 
       adapter.Fill(dt); 
       conn.Close(); 
       for (int i = 0; i < dt.Rows.Count; i++) 
       { 
        foreach (DataRow row in dt.Rows) 
        { 
         //Here I am getting following error 
         // Index was out of range. Must be non-negative and less than the size of the collection. 
         empList[i].uid = row["uid"].ToString(); 
         empList[i].fname = row["fname"].ToString(); 
         empList[i].lname = row["lname"].ToString(); 
        } 
       } 
       return empList; 
      } 

而且ModelGetEmployeeList類就像是這個 -

public class ModelGetEmployeeList 
    {  
     public string uid { get; set; } 
     public string fname { get; set; } 
     public string lname { get; set; } 
    } 

回答

0

因爲你empList是空的。

的正確方法爲ModelGetEmployeeList添加到列表是:

ModelGetEmployeeList employee; 

foreach (DataRow row in dt.Rows) 
{ 
    employee = new ModelGetEmployeeList(); 
    employee.uid = row["uid"].ToString(); 
    employee.fname = row["fname"].ToString(); 
    employee.lname = row["lname"].ToString(); 

    empList.Add(employee); 
} 
+1

您好@Kael,感謝糾正。工作得很好。 – Dipak

+0

沒問題@DipakAkhade – KaeL

+0

無需在數據適配器處理它時打開和關閉連接 –

相關問題