如何将DataGridView内容转换为List<>自定义对象?

时间:2014-01-10 05:18:18

标签: c# winforms list datagridview custom-object

我正在使用C#编写的Windows窗体应用程序。

我找到了某人关于如何从List<>控件创建DataGridView的建议,但我在如何提取单元格值方面需要更多帮助。

这是给出的代码;假设dataGridView1中的两列是NameAddress 如何构建List<ProjList>对象?

foreach (DataGridViewRow dr in dataGridView1.Rows)
{
    ProjList = new List<ProjectMasterRec>();

    foreach (DataGridViewCell dc in dr.Cells)
    {
        // build out MyItem
        // based on DataGridViewCell.OwningColumn and DataGridViewCell.Value
        // how do we code this?
    }

    ProjList.Add(item);
}

3 个答案:

答案 0 :(得分:4)

尝试这种方式

创建班级类型列表

List<ProjectMasterRec>() ProjList = new List<ProjectMasterRec>(); 

确保该类型的列表属于Datagridview

中的数据类型
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
    //Create object of your list type pl
    ProjectMasterRec pl = new ProjectMasterRec();
    pl.Property1 = dr.Cells[1].Value;
    pl.Property2 = dr.Cells[2].Value;
    pl.Property3 = dr.Cells[3].Value;

    //Add pl to your List  
    ProjList.Add(pl);     
}

答案 1 :(得分:2)

如果您能够使用LINQ,您可以这样做:

var projectList = (from row in dataGridView1.Rows.OfType<DataGridViewRow>()
                   select new ProjectMasterRec() 
                   { Name = row.Cells["Name"].Value.ToString(),
                     Address = row.Cells["Address"].Value.ToString() 
                   }).ToList();

答案 2 :(得分:0)

以下内容应该可以使用,<key>BugsnagAPIKey</key> <string>API KEY</string> 应该是您需要的类型的数组,您可以使用myArray找出数组的大小。

(DataGrid1.DataSource as BindingSource).List.Count