我有一个通用的对象列表.每个对象有9个字符串属性.我想将该列表转换为可以传递给datagridview的数据集......最好的方法是什么?
Ben*_*ill 70
我为回答这个问题而道歉,但我认为这是查看我的最终代码的最简单方法.它包含可为空类型和空值的修复程序:-)
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);
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
//go through each property on T and add each value to the table
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;
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*ter 13
您是否尝试过直接将列表绑定到datagridview?如果没有,请首先尝试,因为它会为您节省很多痛苦.如果您已经尝试过,请告诉我们出了什么问题,以便我们为您提供更好的建议.数据绑定根据数据对象实现的接口提供不同的行为.例如,如果你的数据对象只实现IEnumerable(例如List),你会得到非常基本的单向绑定,但如果它实现IBindingList以及(如BindingList,DataView),那么你得到双向绑定.
小智 12
上面有Lee的扩展代码有一个错误,你需要在迭代列表中的项目时将新填充的行添加到表t中.
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);
//add a column to table for each public property on T
foreach(var propInfo in elementType.GetProperties())
{
t.Columns.Add(propInfo.Name, propInfo.PropertyType);
}
//go through each property on T and add each value to the table
foreach(T item in list)
{
DataRow row = t.NewRow();
foreach(var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null);
}
//This line was missing:
t.Rows.Add(row);
}
return ds;
Run Code Online (Sandbox Code Playgroud)
}
您可以创建一个扩展方法,通过反射添加所有属性值:
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);
//add a column to table for each public property on T
foreach(var propInfo in elementType.GetProperties())
{
t.Columns.Add(propInfo.Name, propInfo.PropertyType);
}
//go through each property on T and add each value to the table
foreach(T item in list)
{
DataRow row = t.NewRow();
foreach(var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null);
}
}
return ds;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124988 次 |
| 最近记录: |