s

C# .net generic list to data table edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 22 November 2023 | 593

This C# method, ToDataTable, converts a generic list (List) of items into a DataTable. It starts by creating a new DataTable with a name derived from the type of the items in the list (T). The method then retrieves all public properties of T using reflection and adds columns to the DataTable corresponding to each property. The column types are determined, accounting for nullable types. For each item in the list, it creates a row in the DataTable, populating it with the values of the properties. This method is particularly useful for converting collections of objects into a tabular format, often needed for data binding in UI applications or for further data manipulation and analysis.

List to Data Table Code

        public static DataTable ToDataTable(this List items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                //Defining type of data column gives proper data table 
                var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name, type);
            }
            foreach (T item in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i  )
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }
            //put a breakpoint here and check datatable
            return dataTable;
        }