【问题标题】:How to bind List<dynamic> to datagridview in c# windows form如何在 c# windows 窗体中将 List<dynamic> 绑定到 datagridview
【发布时间】:2017-08-17 14:40:31
【问题描述】:

我的代码是

List<dynamic> source=GetDatagridSource();
datagridview1.AutoGenerateColumns = true;
datagridview1.DataSource = source;

这里GetDatagridSource()以List的形式返回数据,列数是动态的。(列数不固定)。

我想将此结果绑定到 datagridview1。

【问题讨论】:

    标签: .net c#-4.0 datagridview windows-applications


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2011-06-09
      • 1970-01-01
      • 2016-11-04
      相关资源
      最近更新 更多