【问题标题】:How to convert the DataGridView content into a List<> of custom objects?如何将 DataGridView 内容转换为自定义对象的 List<>?
【发布时间】:2014-01-10 05:18:18
【问题描述】:

我正在开发一个用 C# 编写的 Windows 窗体应用程序。

我发现有人建议如何从DataGridView 控件创建List&lt;&gt;,但我需要更多关于如何提取单元格值的帮助。

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

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

【问题讨论】:

  • 是否要获取所有行列数据并以字符串的形式作为一条记录插入到列表中?

标签: c# winforms list datagridview custom-object


【解决方案1】:

试试这个方法

创建您的班级类型列表

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

【讨论】:

    【解决方案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();
    

    【讨论】:

    • 我在您的 Linq 中收到一个错误,即 dgvTest 在当前上下文中不存在。如何将 var projectList 转换为 List?当我们使用 .ToList() 转换查询时,为什么我们不能直接分配给列表。我不想使用 var,因为我稍后会使用 list。
    • @user2026794 - 变量dgvTest 用于说明。使用您的实际变量dataGridView1,我也更新了我的答案。 var 是隐式本地类型,它与System.Object 不同,所以在上述情况下,var 变为List&lt;ProjectMasterRec&gt;
    【解决方案3】:

    以下应该可以工作,myArray 应该是您需要的类型的数组,您可以使用(DataGrid1.DataSource as BindingSource).List.Count 找出数组大小。

    (DataGrid1.DataSource as BindingSource).List.CopyTo(myArray, 0);
    

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 2014-02-15
      • 1970-01-01
      • 2011-01-15
      • 2014-04-17
      • 2018-05-08
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多