List e datatable

martedì 18 novembre 2008 - 09.03

kintaro Profilo | Junior Member

Ciao a tutti,
volevo postare il mio problema.
ho un oggetto che restituisce una collection List<T> e possibile associarlo ad un datatable?

ciao
Fabio

llamanna Profilo | Junior Member

Potresti usare il seguente metodo:

public DataTable ConvertTo<T>(IList<T> list)
{

Type entityType = typeof(T);
DataTable table = new DataTable(entityType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

foreach (PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name, prop.PropertyType);
}



foreach (T item in list)
{
DataRow row = table.NewRow();

foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}

table.Rows.Add(row);
}

return table;
}

Laura.
http://lauralamanna.blogspot.com/

kintaro Profilo | Junior Member

Grazie tante!!
veramente perfetto l'esempio e codice pulito!
ciao
Fabio

llamanna Profilo | Junior Member

Prego
Laura.
http://lauralamanna.blogspot.com/
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?

Dopo esserti registrato potrai chiedere
aiuto sul nostro Forum oppure aiutare gli altri

Consulta le Stanze disponibili.

Registrati ora !
Copyright © dotNetHell.it 2002-2025
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5