AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Friday 3 March 2017

How to convert any generic type list to Data table?

In this article I am going to discuss how to convert any type of list to data table. Please check below code to convert the generic type to data table.

public static DataTable ToDataTable<T>(List<T> items)
            DataTable dataTable = new DataTable(typeof(T).Name);
            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
            PropertyInfo[] propertyInfoArray = properties;
            for (int i = 0; i < (int)propertyInfoArray.Length; i++)
                PropertyInfo propertyInfo = propertyInfoArray[i];
            foreach (T item in items)
                object[] value = new object[(int)properties.Length];
                for (int j = 0; j < (int)properties.Length; j++)
                    value[j] = properties[j].GetValue(item, null);
            return dataTable;

Here I am using the reflection to get the property-info & generate the data table columns & then filling the row values one by one in the data table.


Post a Comment

  • Popular Posts
  • Comments