Question:
Can't convert an object of type 'System.Collections.Generic.List to type 'System.Data.DataSet'?
After making a query from a report, I'm saving the data in a list and showing the data on the screen, but I have an option to export the data to Excel , so to not repeat the query I'm saving the data in a session.
Session
:
repeater_teste.DataSource = retorno;
Session["Ultimo_Relatorio"] = retorno
In the export option I'm doing it this way (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 says it was possible .
Answer:
Tip
I honestly don't see a good reason to do this. That is, it's possible to simply make a list the binding of a DataGridView
, so why bother doing all this conversion?
Ex.:
dg.DataSource = minhaLista;
Reply
Anyway, here's some 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;
}