Mysql 索引超出范围。必须为非负数且小于集合的大小

Mysql 索引超出范围。必须为非负数且小于集合的大小,mysql,c#-4.0,Mysql,C# 4.0,我有下面的代码来获取对象中的表数据,但我得到了错误,我不知道我错在哪里 public List<ModelGetEmployeeList> GetEmployeeList() { List<ModelGetEmployeeList> empList = new List<ModelGetEmployeeList>(); DataTable dt = new Data

我有下面的代码来获取对象中的表数据,但我得到了错误,我不知道我错在哪里

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

因为您的
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);
}

因为您的
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);
}

无问题@dipakakhade,无需在数据适配器处理时打开和关闭连接无问题@dipakakhade,无需在数据适配器处理时打开和关闭连接