我的代码是
List<dynamic> source=GetDatagridSource();
datagridview1.AutoGenerateColumns = true;
datagridview1.DataSource = source;
这里 GetDatagridSource()以List的形式返回具有动态列数的数据。(列数不固定)。
我想将此结果绑定到datagridview1。
答案 0 :(得分:1)
我知道这个问题已经过时了,但它可能有助于有人这样做。
从动态对象创建DataTable并将DataTable绑定到GridView
public static DataTable GetDataTableFromDynamicObject ( List<dynamic> listData )
{
DataTable table = new DataTable ( );
if ( listData.Count > 0 )
{
var firstRow = ( IEnumerable<KeyValuePair<string, JToken>> ) ( JObject ) listData.First ( );
foreach ( KeyValuePair<string, JToken> property in firstRow.OrderBy ( x => x.Key ) )
table.Columns.Add ( new DataColumn ( property.Key ) );
foreach ( var data in listData )
{
DataRow row = table.NewRow ( );
var record = ( IEnumerable<KeyValuePair<string, JToken>> ) ( JObject ) data;
foreach ( KeyValuePair<string, JToken> kvp in record )
{
row [ kvp.Key ] = kvp.Value;
}
table.Rows.Add ( row );
}
}
return table;
}