Responsive Ads Here

Wednesday, June 20, 2012


Convert Generic List collection to DataTable in C#

This post describes how to convert generic list collection to datatable

First Import following namespace

using System.Xml;
using System.IO;
using System.ComponentModel;

Setp 1 :First Create one Entity

public class City
{
        public string CityCode { get; set; }
        public string CityName { get; set; }
}

Step 2: Create Method to bind List Collection and Convert to Datatable

public void BindCityFromXML()
{
         string filepath = @"C:\city.xml";
         DataSet ds = new DataSet();
         ds.ReadXml(filepath);
         List<City> CityColl= new List<City>();
         DataTable CityTable = new DataTable();
         foreach (DataRow dr in ds.Tables[0].Rows)
        {
               City ct = new City();
               ct.CityCode = dr["code"].ToString();
               ct.CityName = dr["Name"].ToString();
               CityColl.Add(ct);
        }
        CityTable = ConvertTo<City>(CityColl);
}

Step 3: Write Following Method

public DataTable ConvertTo<T>(IList<T> lst)
{
      DataTable tbl = CreateTable<T>();
      Type entType = typeof(T);
      PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
      foreach (T item in lst)
     {
              DataRow row = tbl.NewRow();
             foreach (PropertyDescriptor prop in properties)
             {
                    row[prop.Name] = prop.GetValue(item);
             }
             tbl.Rows.Add(row);
      }
      return tbl;
}

public DataTable CreateTable<T>()
{
           Type entType = typeof(T);
           DataTable tbl = new DataTable(entType.Name);
           PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
           foreach (PropertyDescriptor prop in properties)
                 tbl.Columns.Add(prop.Name, prop.PropertyType); return tbl;
}

No comments:

Post a Comment