2013-09-29 16 views
24

Come può convertire un elenco per un DataTableCome compilare un DataTable con la lista <T>

[Serializable] 
public class Item 
{ 
    public string Name { get; set; } 
    public double Price { get; set; } 
    public string @URL { get; set; } 

    public Item(string Name, string Price, string @URL) 
    { 
     this.Name = Name; 
     this.Price = Convert.ToDouble(Price); 
     [email protected] = @URL; 
    } 

    public override string ToString() 
    { 
     return this.Name; 
    } 
} 

Ho provato ad utilizzare:

static DataTable ConvertToDatatable(List<Item> list) 
{ 
    DataTable dt = new DataTable(); 

    dt.Columns.Add("Name"); 
    dt.Columns.Add("Price"); 
    dt.Columns.Add("URL"); 
    foreach (var item in list) 
    { 
     dt.Rows.Add(item.Name, Convert.ToString(item.Price), item.URL); 
    } 

    return dt; 
} 

Ora sto ricevendo una scatola di presentarsi, ma il suo vuoto! Aiuto!! Cosa posso fare per fare in modo che la scatola abbia effettivamente i dati?

+1

Si dice che 'itemDataView' è nullo. Che cosa è esattamente e da dove viene? Questo sembra un altro problema alla conversione di un 'List ' in un 'DataTable' –

+0

itemDataView è ciò che è stato generato dalla toolbox di windowsform – MikaAK

+0

Si prega di chiarire il problema. Il tuo titolo dice che stai avendo problemi con la generazione di 'dataTable'. Ma sembra che non sia affatto il problema. Il tuo problema è con 'itemDataView'. – Muctadir

risposta

18

Prova questa

static DataTable ConvertToDatatable(List<Item> list) 
{ 
    DataTable dt = new DataTable(); 

    dt.Columns.Add("Name"); 
    dt.Columns.Add("Price"); 
    dt.Columns.Add("URL"); 
    foreach (var item in list) 
    { 
     var row = dt.NewRow(); 

     row["Name"] = item.Name; 
     row["Price"] = Convert.ToString(item.Price); 
     row["URL"] = item.URL; 

     dt.Rows.Add(row); 
    } 

    return dt; 
} 
+0

Sto ancora ricevendo che DataGridView è nullo – MikaAK

+0

Quindi il tuo problema non è con la conversione, è con il controllo 'DataGridView' che hai aggiunto al tuo modulo. Prova a rimuoverlo e riaggiungendolo e cambiando il nome in qualcosa di significativo. –

+0

E FUNZIONA GRAZIE !! scusa ma il suo è il codice che ho usato il datagridview remove e readd ha funzionato – MikaAK

2

ho anche dovuto trovare una soluzione alternativa, come nessuna delle opzioni elencate qui ha funzionato nel mio caso. Stavo usando un oggetto IEnumerable ei dati sottostanti erano un oggetto IEnumerable e le proprietà non potevano essere enumerate. Questo ha fatto il trucco:

// remove "this" if not on C# 3.0/.NET 3.5 
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data) 
{ 
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList(); 

    PropertyDescriptorCollection props = null; 
    DataTable table = new DataTable(); 
    if (list != null && list.Count > 0) 
    { 
     props = TypeDescriptor.GetProperties(list[0]); 
     for (int i = 0; i < props.Count; i++) 
     { 
      PropertyDescriptor prop = props[i]; 
      table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); 
     } 
    } 
    if (props != null) 
    { 
     object[] values = new object[props.Count]; 
     foreach (T item in data) 
     { 
      for (int i = 0; i < values.Length; i++) 
      { 
       values[i] = props[i].GetValue(item) ?? DBNull.Value; 
      } 
      table.Rows.Add(values); 
     } 
    } 
    return table; 
} 
32

Nel caso in cui si dispone di una proprietà nullable nel vostro oggetto di classe:

private static DataTable ConvertToDatatable<T>(List<T> data) 
{ 
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); 
    DataTable table = new DataTable(); 
    for (int i = 0; i < props.Count; i++) 
    { 
     PropertyDescriptor prop = props[i]; 
     if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) 
      table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); 
     else 
      table.Columns.Add(prop.Name, prop.PropertyType); 
    } 

    object[] values = new object[props.Count]; 
    foreach (T item in data) 
    { 
     for (int i = 0; i < values.Length; i++) 
     { 
      values[i] = props[i].GetValue(item); 
     } 
     table.Rows.Add(values); 
    } 
    return table; 
} 
Problemi correlati