日期:2014-05-20  浏览次数:20946 次

把用Linq 取得的数据放到DataTable去
表 : SaleOrder 
Id ,Name ,Flag, Date

DataClassesDataContext db =new DataClassesDataContext();

var SaleSource =from sale in db.SaleOrder
  where sale.Flag == 0 || sale.Flag == null
  select sale;
现在想把 SaleSourse 转换成 DataTable

各位大虾 求救!!!!

------解决方案--------------------
public static DataTable CopyToDataTable<T>(this IEnumerable<T> array)
{
var ret = new DataTable();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
ret.Columns.Add(dp.Name, dp.PropertyType);
foreach (T item in array)
{
var Row = ret.NewRow();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
Row[dp.Name] = dp.GetValue(item);
ret.Rows.Add(Row);
}
return ret;
}

------解决方案--------------------
拖个DataGridView 把SaleSource 绑定到DataGridView 
然后再放到DataTable 中

DataGridView.DataSource =SaleSource;
public DataTable GetTable(DataGridView dv)
{

DataTable dt = new DataTable();
DataColumn dc;
for (int i = 0; i < dv.Columns.Count; i++)
{
dc = new DataColumn();
dc.ColumnName = dv.Columns[i].HeaderText.ToString();
dt.Columns.Add(dc);
}
for (int j = 0; j < dv.Rows.Count; j++)
{
DataRow dr = dt.NewRow();
for (int x = 0; x < dv.Columns.Count; x++)
{
dr[x] = dv.Rows[j].Cells[x].Value;
}
dt.Rows.Add(dr);
}
return dt;

}