Monday, July 11, 2016

List to Datatable Converter Using C#

In this article I will describe you how to convert a List objects to a DataTable.


//List to Datatable Converter
   public static DataTable ListToDataTable<T>(IList<T> data)
   {
      DataTable table = new DataTable();

      //special handling for value types and string
      if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
      {

         DataColumn dc = new DataColumn("Value");
         table.Columns.Add(dc);
         foreach (T item in data)
         {
            DataRow dr = table.NewRow();
            dr[0] = item;
            table.Rows.Add(dr);
         }
      }
      else
      {
         PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
         //Get all the properties
         foreach (PropertyDescriptor prop in properties)
         {
            //Setting column names as Property names
            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)
            {
               try
               {
                  //inserting property values to datatable rows
                  row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
               }
               catch (Exception ex)
               {
                  row[prop.Name] = DBNull.Value;
                  var error = ex.Message;
               }
            }
            table.Rows.Add(row);
         }
      }
      return table;
   }

  protected void Button1_Click(object sender, EventArgs e)
  {
     List<string[]> list = new List<string[]>();
     list.Add(new string[] { "Column 1", "Column 2", "Column 3" });
     list.Add(new string[] { "Row 2", "Row 2" });
     list.Add(new string[] { "Row 3" });

     // Convert to DataTable.
     DataTable table = ListToDataTable(list);
     GridView1.DataSource = table;

  }