Tuesday, 17 July 2012

Datatable to List<>


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Xml;

namespace WindowsFormsApplication1
{
    public static class ListDev
    {
        public static List<T> ConverttoList<T>(this DataTable dt)
        {
            List<T> lst = new System.Collections.Generic.List<T>();
            Type tClass = typeof(T);
            PropertyInfo[] pClass = tClass.GetProperties();
            List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
            T cn;
            foreach (DataRow item in dt.Rows)
            {
                cn = (T)Activator.CreateInstance(tClass);
                foreach (PropertyInfo pc in pClass)
                {
                    // Can comment try catch block.
                    try
                    {
                        DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                        if (d != null)
                            pc.SetValue(cn, item[pc.Name], null);
                    }
                    catch
                    {
                    }
                }
                lst.Add(cn);
            }
            return lst;
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
                 
        static DataTable GetTable()
        {
            //
            // Here we create a DataTable with four columns.
            //
            DataTable table = new DataTable();
            table.Columns.Add("Dosage", typeof(string));
            table.Columns.Add("Drug", typeof(string));
         

            //
            // Here we add five DataRows.
            //
            table.Rows.Add("25", "Indocin");//, "David", DateTime.Now);
            table.Rows.Add("50", "Enebrel");//, "Sam", DateTime.Now);
            table.Rows.Add("10", "Hydralazine");//, "Christoff", DateTime.Now);
            table.Rows.Add("21", "Combivent");//, "Janet", DateTime.Now);
            table.Rows.Add("100", "Dilantin");//, "Melanie", DateTime.Now);
            return table;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<Product> lst = ListDev.ConverttoList<Product>(GetTable());
        }
       
    }

    public class Product
    {
        public string Dosage { get; set; }
        public string Drug { get; set; }
        public override string ToString()
        {
            return "Dosage : "  + Dosage+", Drug : " + Drug;
        }


    }



}