简体   繁体   English

如何将datagridview转换为对象列表?

[英]How to convert a datagridview to an objects list?

I have a datagridview which is having two columns. 我有一个datagridview有两列。 Each row is containing a record. 每行都包含一条记录。 I want to get each record to a list of objects.. Each row is having two values and I want to get those two values to two object attributes. 我想将每个记录都保存到对象列表中。每行都有两个值,并且我想将这两个值添加到两个对象属性中。 Row has values id and name I want to read the values to obj.id and obj.name. 行具有值id和名称,我想读取obj.id和obj.name的值。

Since there is no code samples in your question, it is hard to guess how you have populated your DataGridView . 由于您的问题中没有代码示例,因此很难猜测您是如何填充DataGridView However, here are 2 likely scenarios: 但是,这里有两种可能的情况:

Assuming you bound your DatagridView to a DataTable : 假设您将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);
}

Or, you can access the data grid view directly: 或者,您可以直接访问数据网格视图:

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

As I said, those are just examples as you may have used a strong typed DataTable or any other type of Datasource, but still, the main Idea remains the same. 就像我说的那样,这些只是示例,您可能使用了强类型的DataTable或任何其他类型的数据源,但是主要的想法仍然相同。

Example

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM