从DataTable中的行获取数据?

时间:2011-02-25 01:31:25

标签: c# datatable rows

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase excelFile)
    {
        if (excelFile != null)
        {
            /* Snip for brevity. */
            var ds = new DataSet();
            adapter.Fill(ds, "results");
            DataTable data = ds.Tables["results"];

            var people = new List<Person>();

            foreach (var row in data.Rows)
            {
                Person newPerson = new Person(){
                    Id = row?,
                    Name = row?,
                    LastName = row?,
                    DateOfBirth = row?
                };

                people.Add(newPerson);
            }

            return View();
        }

        return RedirectToAction("Error", "Upload");                      
    }

如何检索数据表中包含的信息?我已经检查了MSDN文档,但它们似乎只显示如何以编程方式创建新的DataTable而不是如何检索数据。

感谢您的时间。

2 个答案:

答案 0 :(得分:1)

Person newPerson = new Person(){
                    Id = (int)row["Id"],
                    Name = row["Name"].ToString(),
                    LastName = row["LastName"].ToString(),
                    DateOfBirth = (DateTime)row["DateOfBirth"]
                };

答案 1 :(得分:0)

您可以撰写row.Field<DateTime>("DateOfBirth")