We help IT Professionals succeed at work.

How can i pass my list to a DataTable  and Load same to a Grid

Olukayode Oluwole
on
I have a List in my c#  application prepared using LINQ

The list is generated and i need to pass it to a ListToDataTable  processor in my Library

before loading to a Grid

The  List to Datatable Script  in my Library is as shown below

[] public static class ListToDataTableProcessor
    {

        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection properties =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;
        }
    }[/code]

My application LINQ  script that generates the List is shown below with the last 2 lines flagged.

I am trying to pass the list to the Processor and return a DataTable  (see screen below)

List to DataTable Script
The list generation is ok. I just do not know how to correct the error reported

and how to pass the list to the processor and get the returned Table

I will be Grateful for any Help

Thank

Olukay
Comment
Watch Question

Developer
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
You won't create an instance of the processor, instead you would simply call the method as if it belongs to the List; e.g. -
variations.ToDataTable();

Open in new window

Proof of concept -

Form1.cs -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace EE_Q29174676
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void OnLoad(object sender, EventArgs e)
        {
            dataGridView1.DataSource = (from i in Enumerable.Range(0, 20) 
                                        select new 
                                        { 
                                            Id = i, 
                                            Name = $"Person{i}", 
                                            Birthdate = DateTime.Now.AddMonths(-(i * 9)), 
                                            IsWorking = Convert.ToBoolean(i & 1) 
                                        }).ToDataTable();
        }
    }

    static class Extensions
    {
        public static DataTable ToDataTable<T>(this IEnumerable<T> source)
        {
            Type entity = typeof(T);
            DataTable table = new DataTable(entity.Name);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entity);
            foreach (PropertyDescriptor property in properties)
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]);
                else
                    table.Columns.Add(property.Name, property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in source)
            {
                for (int i = 0; i < values.Length; i++)
                    values[i] = properties[i].GetValue(item);
                table.Rows.Add(values);
            }
            return table;
        }
    }
}

Open in new window

Form1.Designer.cs -
namespace EE_Q29174676
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGridView1
            // 
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dataGridView1.Location = new System.Drawing.Point(0, 0);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.ReadOnly = true;
            this.dataGridView1.RowHeadersVisible = false;
            this.dataGridView1.Size = new System.Drawing.Size(576, 326);
            this.dataGridView1.TabIndex = 0;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(576, 326);
            this.Controls.Add(this.dataGridView1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.OnLoad);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dataGridView1;
    }
}

Open in new window

Produces the following output -Capture.PNG-saige-
Olukayode OluwoleSystems Analyst

Author

Commented:
Thanks .

You always made my day with your proof of concept