Introduction

In this post, I will explain how you can convert generic list to DataTable. In the below example I am having a list of colors that I will convert to DataTable.

Example : Convert generic list to DataTable

 private void FillData()
  {
  List<string> _ColorList = new List<string>(); // List to be converted into DataTable
  _ColorList.Add("Red");
  _ColorList.Add("White");
  _ColorList.Add("Black");
  _ColorList.Add("Green");
  _ColorList.Add("Blue");
  DataTable _ResultDataTable = ConvertListToDataTable(_ColorList);
  }

 public static DataTable ConvertListToDataTable<T>(IList<T> p_ColorList)
  {
  DataTable _DataTable = new DataTable();
  if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
  {
  DataColumn _DataColumn = new DataColumn("ColorList");
  _DataTable.Columns.Add(_DataColumn);

  foreach (T item in p_ColorList)
  {
  DataRow dr = _DataTable.NewRow();
  dr[0] = item;
  _DataTable.Rows.Add(dr);
  }
  }
  else
  {
  PropertyInfo[] _PropertyInfo = typeof(T).GetProperties();
  foreach (PropertyInfo pi in _PropertyInfo)
  {
  DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
  _DataTable.Columns.Add(dc);
  }

  for (int item = 0; item < p_ColorList.Count(); item++)
  {
  DataRow _DataRow = _DataTable.NewRow();
  for (int property = 0; property < _PropertyInfo.Length; property++)
  {
  _DataRow[property] = _PropertyInfo[property].GetValue(p_ColorList[item], null);
  }
  _DataTable.Rows.Add(_DataRow);
  }
  }
  _DataTable.AcceptChanges();
  return _DataTable;
  }

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website