问题
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 ExpandoObject
s 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