Question

I want to populate a DataTable using reflection, not knowing what the column types will be at compile time. I'm going to have an object that implements an interface, say 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.

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.

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top