【问题标题】:How to convert a datagridview to an objects list?如何将 datagridview 转换为对象列表?
【发布时间】:2014-05-12 02:47:19
【问题描述】:

我有一个数据网格视图,它有两列。每行包含一条记录。我想将每条记录获取到对象列表。每行都有两个值,我想将这两个值获取到两个对象属性。行有值 id 和 name 我想将值读取到 obj.id 和 obj.name。

【问题讨论】:

  • 显示你目前尝试过的代码。

标签: c# list object datagridview


【解决方案1】:

由于您的问题中没有代码示例,因此很难猜测您是如何填充 DataGridView 的。但是,这里有两种可能的情况:

假设您将DatagridView 绑定到DataTable

List<MyClass> list = new List<MyClass>();
DataTable dt = DataGridView1.DataSource as DataTable;
foreach (DataRow row in dt.Rows)
{
    MyClass myObject = new MyClass();
    myObject.id = (int)row["Id"]; // Assuming the column is called "Id"
    myObject.Name = (string)row["Name"];// Assuming the column is called "Name"
    list.Add(myObject);
}

或者,您可以直接访问数据网格视图:

List<MyClass> list = new List<MyClass>();
foreach (DataGridViewRow row in DataGridView1.Rows)
{
    MyClass myObject = new MyClass();
    myObject.id = (int)row.Cells["Id"].Value; // Assuming the column is called "Id"
    myObject.Name = (string)row.Cells["Name"].Value;// Assuming the column is called "Name"
    list.Add(myObject);
}

正如我所说,这些只是示例,因为您可能使用过强类型 DataTable 或任何其他类型的数据源,但主要思想仍然相同。

【讨论】:

    【解决方案2】:

    例子

    List<Class1> List1 = new List<Class>();
    foreach (DataGridViewRow row in DataGridView.Rows)
    {
         List1.Add(new Class1(row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[2].Value.ToString(), int.Parse(row.Cells[3].Value.ToString()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 2021-11-25
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      相关资源
      最近更新 更多