Recently I use WPF, I have a list obtained through Dapper.
In Windows Forms I do:
List<Person>list = new List<Person>();
using(var conn = new SqlConnection(connection))
{
list = conn.Query<Person>(query).ToList();
}
datagridview = list;
How can I do the same thing in WPF? That is, display the contents of list on a datagridview?
CodePudding user response:
Set the ItemsSource
property of the WPF DataGrid
if that's the control you are using:
List<Person> list = new List<Person>();
using (var conn = new SqlConnection(connection))
{
list = conn.Query<Person>(query).ToList();
}
dataGrid.ItemsSource = list;
Then you will get a column for each public property of the Person
class by default.
<DataGrid x:Name="dataGrid" />
CodePudding user response:
This called binding.
There is a good tutorial here : https://wpf-tutorial.com/en/76/le-controle-listview/listview-data-binding-et-itemtemplate/
And instead of using a List, use a ObservableCollection.
For example, in your situation :
<DataGrid x:Name="dgdPersons" VerticalAlignment="Stretch" AutoGenerateColumns="False" Width="300" Height="800">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Width="*" Header="Name" />
<DataGridTemplateColumn Header="Actions">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Cursor="Hand" Width="50" Height="26" Content="Clic for action" Margin="2" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
And the code begind :
public class Person
{
public string Name { get; set; }
}
ObservableCollection<Person> allPersons = new ObservableCollection<Person>();
allPersons.Add(new Person() { Name = "Bryan" });
allPersons.Add(new Person() { Name = "Karen" });
InitializeComponent();
dgdChapitres.ItemsSource = allPersons;
Don't forget that you will need to implement INotifyPropertyChange in your Person class if you want it to be in real time updated.