How do you bind Dapper query result to WPF DataGrid

.net c# dapper data-binding wpf

Question

Here's my code. It produces a bound grid with the correct number of rows, however the cells are empty.

XAML

<DataGrid
  Name="grid" 
  ItemsSource="{Binding}"
  AutoGenerateColumns="True" />

Code behind

grid.DataContext = cn.Query("select * from SomeTable");

Accepted Answer

From the docs, your syntax there -- cn.Query("sql") -- returns a list of dynamic-typed objects (IEnumerable<dynamic>). That won't work for the DataGrid auto-columns, which looks for concrete members to generate its columns. I'd suggest creating a simple entity class for SomeTable to map the properties and then using cn.Query<SomeTableEntity>("select * from SomeTable");.


Expert Answer

If you use the non-generic version of Query, it returns a dynamic representation of the data. The dynamic API is not suitable for most UI data-bindings. It would be preferable to use the generic Query<T> API to load the data into types that have defined properties.

At a complete push, it would also theoretically be possible to implement ITypedList on the data and expose the properties accordingly. But that is quite a lot of work for not so much gain.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow