ZeroBased_IX
ZeroBased_IX

Reputation: 2727

Populate DataTable dynamically using Object Properties

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;
}

Upvotes: 0

Views: 4937

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Use this extension method which is for List and make your User object as List<User> and simply call ToDataTable() on its instance.

Here is extension method:

public static class ListExtensions
{
   public static DataTable ToDataTable<T>(this List<T> iList)
   {
    DataTable dataTable = new DataTable();
    PropertyDescriptorCollection propertyDescriptorCollection =
        TypeDescriptor.GetProperties(typeof(T));
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
        Type type = propertyDescriptor.PropertyType;

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            type = Nullable.GetUnderlyingType(type);


        dataTable.Columns.Add(propertyDescriptor.Name, type);
    }
    object[] values = new object[propertyDescriptorCollection.Count];
    foreach (T iListItem in iList)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
        }
        dataTable.Rows.Add(values);
    }
    return dataTable;
  }
}

and you have to simply call it this way:

List<User> users = new List<User>();
DataTable dt = users.ToDataTable();

UPDATE:

The way you are doing you have to iterate over User class properties like this:

PropertyDescriptorCollection propertyDescriptorCollection =
        TypeDescriptor.GetProperties(typeof(User));
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
        Type type = propertyDescriptor.PropertyType;

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            type = Nullable.GetUnderlyingType(type);


        dt.Columns.Add(propertyDescriptor.Name, type);
    }

Just wrote another extension method for single object of a Class:

public static DataTable ToDataTable<T>(this T Item) where T: class
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];

                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(Item);
                }

                dataTable.Rows.Add(values);

            return dataTable;
        }

and call it like this:

Client u = JsonConvert.DeserializeObject<Client>(json);
DataTable dt = user.ToDataTable();

Upvotes: 3

Related Questions