Reputation: 385
I have never converted a list to a DataTable
and write it on a text file but in my attempt my file appears all blank only containing empty braces({})
this is my code:
List<string> list = new List<string>();
foreach (var item in db.Pos)
{
var total = 0;
decimal costo = 0;
for (int i = 1; i <= 31; i++)
{
var value = 0;
if (item.Fecha.Day == i)
{
value = item.Cantidad;
costo = costo + item.Total;
}
total += value;
}
list.Add(item.Descripcion);
list.Add(item.Pdv);
list.Add(item.Rid);
list.Add(((costo / (total + 1)).ToString("C")));
for (int i = 1; i <= 31; i++)
{
var value = 0;
list.Add(value.ToString());
int month = item.Fecha.Month;
if (item.Fecha.Day == i)
{
value = item.Cantidad;
list.Add(value.ToString());
}
}
list.Add(total.ToString());
list.Add((((costo / (total + 1)) * total).ToString("C")));
}
DataTable table = ToDataTable(list);
System.IO.File.WriteAllText(@"\path.txt", table);
This is my function that convert my List<T>
to DataTable
but makes my file empty:
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
Upvotes: 0
Views: 147
Reputation: 333
You haven't passed the data table to the WriteAllText method besides the WriteAllText method doesn't have a parameter for a data table. You will need to loop through the data table and write it manually like this:
http://www.codeproject.com/Questions/244929/How-to-write-datatable-result-in-textfile
Upvotes: 1