Convert an object of type 'System.Collections.Generic.List in type' System.Data.DataSet '?

4
  

Can not convert an object of type 'System.Collections.Generic.List in type' System.Data.DataSet '?

After making a query for a report, I am saving the data in a list and displaying the data on the screen, plus I have an option to export the data to Excel >, so to not repeat the query I am saving the data in a session.

  

Session :

repeater_teste.DataSource = retorno;
Session["Ultimo_Relatorio"] = retorno

In the export option I am doing this (generating error ):

 DataSet ds = (DataSet)Session["Ultimo_Relatorio"];
 DataGrid dg = new DataGrid();
 dg.AllowPaging = false;
 dg.DataSource = ds.Tables[0];
 dg.DataBind();

I found this article that said it was possible .

    
asked by anonymous 17.01.2017 / 16:38

1 answer

4

Tip

I honestly do not see a good reason to do this. That is, you can simply make a list binding of a DataGridView , so why bother doing all this conversion?

>

Ex:

dg.DataSource = minhaLista;

Response

Anyway, here's a code that does exactly what you need

public static DataSet ToDataSet<T>(this IList<T> list)
{
    Type elementType = typeof(T);
    DataSet ds = new DataSet();
    DataTable t = new DataTable();
    ds.Tables.Add(t);

    // Adicionar uma coluna para propriedade pública em T
    foreach (var propInfo in elementType.GetProperties())
    {
        Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

        t.Columns.Add(propInfo.Name, ColType);
    }

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

        foreach (var propInfo in elementType.GetProperties())
        {
            row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
        }

        t.Rows.Add(row);
    }

    return ds;
}
    
17.01.2017 / 16:50