views:

13

answers:

1

I'm trying to use PropertyInfo interate through a class and create a datatable from it. However it returns no values. I'm a little stumped;

public class thetransactions
{
    public string FirstName;
    public string Surname;
    public string PreviousOwner;
    public string NewOwner;
    public string postcode;
    public string[] FileName;
}

Then do the legwork with this code;

theTransactions[] thetransactions = new theTransactions[10];
thetransactions[0] = JsonConvert.DeserializeObject<theTransactions>(mydatastring);

PropertyInfo[] properties = thetransactions.GetType().GetElementType().GetProperties();
DataTable sampletable = new DataTable();
DataColumn dc = null;

foreach (PropertyInfo pi in properties)
{
    dc = new DataColumn();
    dc.ColumnName = pi.Name;
    dc.DataType = pi.PropertyType;
    sampletable.Columns.Add(dc);
}
+2  A: 

The problem is that you're defining normal variables in your thetransactions class and not properties:

public class thetransactions
{
    public string FirstName{get;set;}
    public string Surname{get;set;}
    public string PreviousOwner{get;set;}
    public string NewOwner{get;set;}
    public string postcode{get;set;}
    public string[] FileName{get;set;}
}
Giu
I get a NullReferenceException when I change to look at [0], strange because there are objects present. My only hunch is perhaps some of my properties are null, for example NewOwner has a null value attached. Although I'm not particularly interested in the values, just want to grab the column names and types.
wonea
I've updated my answer; it should solve your problem now. The first version of my answer contained the wrong hint; sorry for that
Giu
Fantastic! I presume PropertyInfo calls the get method for each type?
wonea
The `PropertyInfo` just stores all the information of a property, e.g. its name (`FirstName`) and its type (`System.String`). `GetProperties()` uses the Reflection API to compile an array with information about every property of a class / type.
Giu