如何从datagridview制作列表?

时间:2012-03-07 17:40:51

标签: c# winforms datetime datagridview

我已经从SQL数据库项目下载到我的datagridview,所以我有8列自动生成。

我想要做的是将第5列和第6列的值添加到List。

所以我希望得到类似的东西,但要从细胞中获取值。

 public List<Item> GetItems()
    {
        return new List<Item>(){
           new Item(){Name = "Usage1", dat=  DateTime.Parse("2012-03-06"},
           new Item(){Name = "Usage2", dat=  DateTime.Parse("2012-03-07"}};

    }
 public class Item
    {
        public string Name;
        public datetime dat;

        public Item()
        {
        }
    }

怎么做?

1 个答案:

答案 0 :(得分:0)

您应该能够使用Linq-Objects查询从行中提取数据,然后从每行中的单元格中提取数据。

var data = 
    dataGridView.Rows.Cast<DataGridViewRow>()
    .Select(
        row =>
            new
            {
                 Col5 = row.Cells[Column5.Index].Value,
                 Col6 = row.Cells[Column6.Index].Value,
            })
    .ToList();