如何使用List< Dynamic>与DataGridView.DataSource一样?

如何使用List< Dynamic>与DataGridView.DataSource一样?

问题描述:

我正在尝试将 List< dynamic> 绑定到DataGridView DataSource属性.尽管编译时没有错误,但是也没有显示列.

I'm trying to bind a List<dynamic> to a DataGridView DataSource property. While there are no errors when compiling there are no columns being displayed either.

如果我预先创建了列,我将显示行,但是其中没有数据.

If I pre-create the column I get the rows to display, but there's no data in them.

简单地说,如何在我的DataGridView中正确使用 List< dynamic> 对象?

Simply put, how can I properly use a List<dynamic> object with my DataGridView?

如果我没记错的话,Dapper的动态查询将返回 ExpandoObject 的集合,该集合使您可以动态访问诸如 person之类的属性..Name ,但是基础对象实际上没有 Name 属性.它使用运行时绑定从内部键/值字典提取数据.由于 DataGridView 的默认数据绑定使用反射来获取对象的属性,因此无法找到查询返回的列.

If I remember correctly, Dapper's dynamic query returns a collection of ExpandoObjects that lets you dynamically access properties such as person.Name, but the underlying objects doesn't actually have a Name property. It uses run-time binding to extract the data from an internal key/value dictionary. Since the default data binding for DataGridView uses reflection to get the properties of the objects, it does not find the columns returned from the query.

因此,您有一些选择:

  • 将结果水化为具体类型,而不是 dynamic
  • 指定要显示在 DataGridView 中的列,而不使用默认绑定.
  • 使用类似于此答案的方法,将动态结果转换为 DataTable ..
  • li>
  • Hydrate the result as a concrete type instead of dynamic
  • Specify the columns you want to display in your DataGridView rather than using the default binding.
  • Convert the dynamic result to a DataTable using something similar to this answer.