I'm trying to add an objects properties to a datatable dymamically. I'm trying to stay away from explicitly stating the properties of the object since I want this code to work for every object in my application. I've read the Adding object to DataTable and create a dynamic GridView but this isn't dynamic enough for me since he is explicitly specifying the properties.
private static void Main(string[] args)
{
//Read in JSON from text file
StreamReader fileStream = new StreamReader(@"C:\Users\Aid\Desktop\test.txt");
string json = fileStream.ReadToEnd();
//Deserialise and map to class
Client u = JsonConvert.DeserializeObject<Client>(json);
DataTable dt = new DataTable();
List<string> CliProperties = new List<string>();
//Loop through Object properties and add to Datatable columns
CliProperties = objProps(u);
DataRow newRow = dt.NewRow();
foreach (var prop in CliProperties)
{
dt.Columns.Add(prop);
newRow[prop] = u.prop;
}
Console.ReadKey();
}
/// <summary>
/// Get list of object properties
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static List<string> objProps(Object obj)
{
List<string> Props = new List<string>();
Type objType = obj.GetType();
foreach (PropertyInfo propertyInfo in objType.GetProperties())
{
if (propertyInfo.CanRead)
{
Props.Add(propertyInfo.Name);
}
}
return Props;
}
}
public static class DataColumnCollectionExtensions
{
public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
{
return source.Cast<DataColumn>();
}
}
The problem area for me is:
foreach (var prop in CliProperties)
{
dt.Columns.Add(prop);
newRow[prop] = u.prop;
}
I'm getting the error: 'Client' does not contain a definition for 'prop' and no extension method 'prop' accepting first argument of type 'Client'
I understand why I'm getting the error however I'm unsure how to make it work.
I'm trying to add a new Row with PropertyName newRow[prop]
with the values of the objects property value = u.prop
.
EDIT: The DataTable Column names will be identical to the object property names.
The first iteration of the foreach should be the following:
foreach (var prop in CliProperties)
{
dt.Columns.Add("RefID");
newRow["RefID"] = u.RefID;
}