[英]How to bind a variable-size list of objects containing another variable-size list of objects of to DataGridView in C#
How to bind a variable-size list of objects (here called Record) containing another variable-size list of objects (here called Field) to DataGridView in a way that each the Field object in the inner list bind to a cell (through Value property) and each of the Record object in the outer list bind to a row. 如何通过内部列表中的每个Field对象绑定到单元格的方式(通过Value属性)将包含另一个对象的可变大小列表(此处称为Field)的可变大小的对象列表(此处称为Record)绑定到DataGridView ),外部列表中的每个Record对象都绑定到一行。 The idea is to make a DataGridView dynamically with a variable number of columns based on the number of items in the inner list for each Record object. 这个想法是根据每个Record对象的内部列表中的项目数,动态创建一个具有可变列数的DataGridView。 Here is my code for Record class: 这是我的Record类的代码:
public class Record
{
public List<Field> Fields { get; set; }
}
and the Field class: 和Field类:
public class Field
{
public String Name { get; set; }
public String Value { get; set; }
}
in the main program I have something like: 在主程序中,我有类似以下内容:
public List<Record> Records{ get; set; }
The Records list get filled programmatically and each Record in the list has the same amount of objects in its Fields list. 记录列表以编程方式填充,并且列表中的每个记录在其字段列表中具有相同数量的对象。 Now I want to bind this data to a DataGridView in a way that each Record object in the outer list shows as a row in the table where each of its Fields is aa cell in the DataGridView. 现在,我想将此数据绑定到DataGridView,使外部列表中的每个Record对象在表中显示为一行,其中每个Field在DataGridView中都是一个单元格。 Is that possible? 那可能吗? If so, how can I do it? 如果是这样,我该怎么办?
You can transform it to list of DataGridViewRow
and add those the the DataGridView
您可以将其转换为DataGridViewRow
列表,然后将其添加到DataGridView
First you need to set the columns (this assumes you have a first record at all): 首先,您需要设置列(假设您有第一条记录):
foreach (Field field in this.Records.First().Fields)
{
dgv.Columns.Add(field.Name, field.Name);
}
Then using LINQ transform each Record
to DataGridViewRow
然后使用LINQ将每个Record
转换为DataGridViewRow
IEnumerable<DataGridViewRow> rows = this.Records.Select(rec =>
{
var row = new DataGridViewRow();
row.SetValues(rec.Fields.Select(field => field.Value));
return row;
});
And finally load them to the DataGridView
: 最后将它们加载到DataGridView
:
dgv.Rows.Add(rows);
If you want to use DataSource
you will have to create a DataTable
out of it. 如果要使用DataSource
,则必须从中创建一个DataTable
。
You can create and extension method and use it like this: 您可以创建和扩展方法,并按以下方式使用它:
dgv.DataSource = this.Records.ToDataTable();
The extension class: 扩展类:
public static class RecordListExtensions
{
public static DataTable ToDataTable(this List<Record> records)
{
DataTable table = new DataTable();
foreach (var field in records.First().Fields) { table.Columns.Add(field.Name); }
foreach (var record in records)
{
table.Rows.Add(record.Fields.Select(field => field.Value).ToArray());
}
return table;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.