简体   繁体   English

用反射填充数据表

[英]Populating a DataTable with reflection

I want to populate a DataTable using reflection, not knowing what the column types will be at compile time. 我想使用反射来填充DataTable,而不知道在编译时列类型将是什么。 I'm going to have an object that implements an interface, say IData . 我将有一个实现接口的对象,例如IData

I want the DataTable column schema to reflect the object fields, and the rows of the DataTable to come from a list of IData objects. 我希望DataTable列架构反映对象字段,并且DataTable的行来自IData对象的列表。

So far I have ... 到目前为止,我有...

var listOfData = GetIDataListImplementation();

    var dataTable = new System.Data.DataTable();

    var first = listOfData.FirstOrDefault();

    var type = typeof(fist);
    var props = mainType.GetProperties();

    // Create Table
    foreach (var prop in props)
    {
        dataTable.Columns.Add(new System.Data.DataColumn(prop.Name, prop.PropertyType));
    }

    // Populate Table
    foreach (var dataItem in listOfData)
    {
// STUCK HERE NOT SURE WHAT TO DO
        System.Data.DataRow row = dataTable.NewRow();
        for (int i = 0; i < mainProps.Length; i++)
        {
// HOW DO I GET THE OBJECT PROPERTY VALUE ASSOCIATED WITH THIS TABLE COLUMN?
            row[mainProps[i].Name] = dataItem;
        }
    }

As you can see I'm stuck at the point of actually populating rows with property values of the associated object property type. 如您所见,我陷入了用相关对象属性类型的属性值实际填充行的问题。

You're mostly there, you should be able to do this: 您大部分都在那儿,您应该可以执行以下操作:

foreach (var dataItem in listOfData)
{
    DataRow row = dataTable.NewRow();

    for (int i = 0; i < props.Length; i++)
    {
       row[i] = props[i].GetValue(dataItem);
    }

    dataTable.Rows.Add(row);
}

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

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