Question

I am attempting to use a DataTable to create and populate a group of objects. I was hoping to create one function that would know what type of object to create based on the type passed into the function. Then using either the object returned by Activator.CreateInstance(type) or Reflection, populate the objects fields with the data in the dataset. Here is my function:

private object DataTableToObject(DataTable table, Type type)
{
    var obj = Activator.CreateInstance(type);
    //we are only concerned with the first row here

    var row = table.Rows[0];

    /* do something here to populate the fields of MyObject */
}

I was hoping to call this function like this...

var dataTable1 = DataTableToObject(dataSet.Tables[dataSet.Tables.IndexOf("MyCustomObject")]);
MyCustomObject custObj = DataTableToObject(dataTable1, typeof(MyCustomObject));

Edit: What is the best way to populate the fields in the object at runtime? Do I need to use reflection to get the field names, then using the field names, populate the object somehow?

Solution!

private T DataTableToObject<T>(DataTable table)
{
    var obj = Activator.CreateInstance(typeof(T));

    //we are only concerned with the first row because in our datasets, we should only have one row per table
    var row = table.Rows[0];

    foreach(DataColumn col in table.Columns)
    {
        var propInfo = obj.GetType().GetProperty(col.ColumnName);
        if (propInfo == null) continue;

        object colValue;
        if(propInfo.PropertyType == typeof(Guid))
           colValue = Guid.Parse(row[col.ColumnName].ToString());
        else 
           colValue = Convert.ChangeType(row[col.ColumnName], propInfo.PropertyType);

        propInfo.SetValue(obj, colValue, null);
     }
     return (T) obj;
}
Was it helpful?

Solution

First make the method generic:

private T DataTableToObject<T>(DataTable table)

and then change it up a little:

var obj = Activator.CreateInstance(typeof(T));

and at the end of the method remember to cast it:

return (T)obj;

and now, when you call it, it will look like this:

MyCustomObject custObj = DataTableToObject<MyCustomObject>(dataTable1);

And now how to populate the fields, I would do something like this:

foreach (var col in table.Columns)
{
    var propInfo = obj.GetType().GetProperty(col.Name);
    if (propInfo == null) { continue; }

    propInfo.SetValue(obj, row[col.Name], null);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top