Thursday, 9 February 2012

Convert dictionary to dataTable in C# ?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;


 /* calling */
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Product objProduct = new Product ();
            objProduct.Id = 1;
            objProduct.Name = "Computer";
            objProduct.Description = "Computer is a electronic machine.";
            objProduct.createdDate = System.DateTime.Now;


            Dictionary<string, Product> productDictionary = new Dictionary<string, Product>();
            productDictionary.Add("1", objProduct);

            DataTable RegistrationP= new DataTable ();
            RegistrationP = DictionaryToDataTable.ConvertTo<Product>(productDictionary, "DemoTable");
           
        }


 /* Product Class */
    public class Product
    {
        public Int16 Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime createdDate { get; set; }
    }

/* to Convert Dictionary to DataTable Class */
    class DictionaryToDataTable
    {
        public static DataTable ConvertTo<T>(Dictionary<string, T> list, string dataTableName)
        {
            DataTable table = CreateTable1<T>(dataTableName);
            Type entityType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (KeyValuePair<string, T> item in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    if (prop.PropertyType.Name != "Dictionary`2")
                    {
                        if (prop.PropertyType.FullName == "System.String")
                            if (prop.GetValue(item.Value) == null)
                                row[prop.Name] = prop.GetValue(item.Value);
                            else
                                row[prop.Name] = prop.GetValue(item.Value).ToString().Replace("'", "''");
                        else
                            row[prop.Name] = prop.GetValue(item.Value);
                    }
                table.Rows.Add(row);
            }
            return table;
        }

        public static DataTable CreateTable1<T>(string dataTableName)
        {
            Type entityType = typeof(T);
            DataTable table = new DataTable(dataTableName);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
            foreach (PropertyDescriptor prop in properties)
            {
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            return table;
        }
    }


Hope this helps.

 

No comments:

Post a Comment