2016-08-04 18 views
1

オブジェクトにテーブルデータを取得するコードがありますが、エラーが発生していて、どこが間違っているのか分かりません。あなたのempListが空であるためインデックスが範囲外でした。負でなく、コレクションのサイズより小さくなければならない

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クラスはthis-

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

答えて

0

のようなものです。

あなたのリストに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

データアダプターがそれを処理するので、接続を開いたり閉じたりする必要はありません –

関連する問題

 関連する問題