我是 C# 的新手,在 Stackoverflow.com 上遇到了很多问题,但没有找到满足我要求的解决方案。所以最后在这里发帖。
我的要求是从数据表列名创建动态属性,并将值设置为数据表中的动态属性。最后将数据绑定(bind)到gridview。
所以我决定按照下面的步骤来实现这个功能(如果我错了请纠正我)
我的数据表包含26行10列数据
- 创建 A 类
- 从数据表(列名)向 A 添加动态属性
- 为 A 的属性设置值
- 将 A 类列为 A 类
- 将A的列表绑定(bind)到GridView
我已经完成了以下步骤
1.
[Serializable]
public class A
{
public A()
{
}
}
2 & 3.
DataTable dt = getData();
dynamic expando = new ExpandoObject();
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
var expandoDict = expando as IDictionary<String, Object>;
if (expandoDict.ContainsKey(col.ToString()))
expandoDict[col.ToString()] = row[col.ColumnName].ToString();
else
expandoDict.Add(col.ToString(), row[col.ColumnName].ToString());
}
}
执行上述for循环后,“expando”对象只包含数据表的最后一行。
你能帮我解决第 2 步到第 5 步吗?
最佳答案
据我了解,这段代码可能更符合您的需求。这应该为您将数据放入 expandoList 中。然后,您需要处理与 GridView 的绑定(bind)。
DataTable dt = getData();
List<dynamic> expandoList = new List<dynamic>();
foreach (DataRow row in dt.Rows)
{
//create a new ExpandoObject() at each row
var expandoDict = new ExpandoObject() as IDictionary<String, Object>;
foreach (DataColumn col in dt.Columns)
{
//put every column of this row into the new dictionary
expandoDict.Add(col.ToString(), row[col.ColumnName].ToString());
}
//add this "row" to the list
expandoList.Add(expandoDict);
}
关于c# - 使用数据表创建 ExpandoObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45200579/