เพื่อนลองใช้ code นี้ไปเเปลง generic เป็น datatable ได้ครับ
โค้ด: เลือกทั้งหมด
using System.Collections.Generic;
public partial class UcReport : System.Web.UI.UserControl
{
private List<InputPerdium> listPerdium = null;
protected void Page_Load(object sender, EventArgs e)
{
LoadGridview();
}
private void LoadGridview()
{
try
{
listPerdium = blgInputPD.GetAllItemInputdium();
if (listPerdium.Count >= 1)
{
DataTable dtPD = [color=#FF0000]IEnumerableExt.GenericToDataTable(listPerdium);[/color]
// Let's enjoy it :-)
}
}
}
}
public static class IEnumerableExt
{
public static DataTable GenericToDataTable<T>(this IEnumerable<T> things) where T : class
{
DataTable tbl = new System.Data.DataTable();
bool buildColumns = false;
foreach (var item in things)
{
Type t = item.GetType();
var properties = t.GetProperties();
if (!buildColumns)
{
foreach (var prop in properties)
{
Type ptype = prop.PropertyType;
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
ptype = Nullable.GetUnderlyingType(prop.PropertyType.UnderlyingSystemType);
}
DataColumn col = new DataColumn(prop.Name, ptype);
tbl.Columns.Add(col);
}
buildColumns = true;
}
DataRow row = tbl.NewRow();
foreach (var prop in properties)
{
if (prop.GetValue(item, null) == null)
{
row[prop.Name] = DBNull.Value;
}
else
{
row[prop.Name] = prop.GetValue(item, null);
}
}
tbl.Rows.Add(row);
}
return tbl;
}
}