mysql - 索引超出范围。必须是非负数且小于集合的大小

标签 mysql c#-4.0

我有以下代码来获取对象中的表数据,但出现错误,我不知道哪里错了。

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

最佳答案

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

关于mysql - 索引超出范围。必须是非负数且小于集合的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38760197/

相关文章:

asp.net - 在 App_Code 目录中调试较长的编译时间

c# - 如何使用 C# 在标签或文本框中显示此 linq 查询?

c# - 如何对以文件名作为参数的方法进行单元测试

c# - 如何使用泛型开发适用于 double 和小数的代码

php - 无法获取空 mysql 值

c# - ASP.NET中选择两列后填充多个文本框DropDownList

MySQL:如何重置或更改 MySQL root 密码?

android - 从 MYSQL 获取 JSON 对象到数组

c# - 当路径包含 # 时创建部分 URI

mysql - 安装 DBD::mysql 时缺少 mysql_config 错误