大家中午好。
我有下一个问题:从数据库中获取数据(c# NetFrameWork 5)
//Taka the List
EDBRecList = f1.edb.fn_EDBRecipes().ToList();
// Take the columns name
var Colls = (from t in typeof(fn_EDBRecipes_Result).GetProperties() select t.Name).ToList();
DataTable dt1 = new DataTable();
dt1.Columns.Clear();
dt1.Rows.Clear();
foreach (var c in Colls)
{
dt1.Columns.Add(c);
}
//it`s OK
//but how to fill the table in a loop? referring to columns by their number
//now using the next long process
for (int j = 0; j < EDBRecList.Count; j++)
{
NewString = new string[] {
EDBRecList[j].ID.ToString(),
EDBRecList[j].RecipeName,
EDBRecList[j].RecTypeID.ToString(),
EDBRecList[j].RecTypeName,
EDBRecList[j]. ProdID.ToString(),
EDBRecList[j].ProductCode,
EDBRecList[j].ProdName,
EDBRecList[j].ProductTypeID.ToString(),
EDBRecList[j].ProductSetID.ToString(),
EDBRecList[j].ProdGroupID.ToString(),
EDBRecList[j].ProducedMaterialID.ToString(),
EDBRecList[j].SystemName
};
dt1.Rows.Add(NewString);
}
提前谢谢你
方法在10列上工作。如果有100个呢?
就像获取列名那样使用反射,并使用您的列名列表:
Type elementType = EDBRecList.GetType().GetElementType();
for (int j = 0; j < EDBRecList.Count; j++)
{
NewString = (from col in Colls
select elementType.GetProperty(col).GetValue(EDBRecList[j], null).ToString()
).ToArray();
dt1.Rows.Add(NewString);
}