How can I use a List<Dynamic> as with DataGridView.DataSource? [closed]

白昼怎懂夜的黑 提交于 2021-02-08 12:05:59

问题


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.

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


回答1:


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.

So you have a few options:

  • 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.


来源:https://stackoverflow.com/questions/33828818/how-can-i-use-a-listdynamic-as-with-datagridview-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!