This entry has been published on 2013-11-07 and may be out of date.
Last Updated on 2013-11-07.
Scenario
You have 2 simple MySQL / SQL / SQlite database tables like “customer” and “offer” with a foreign key relation between them (1 customer, * offers).
You want to show the offer table in a DataGrid, and the “customer” column should contain a Combobox with all customers.
Solution
Please note: This description is mainly for WPF beginners who come from .Net Windows Forms, so I will not describe more complex models like MVVM here.
- Create an ADO.NET Entity Framework and generate your database tables, e.g. with the wizard.
- In the DB model properties, set code generation strategy from None to Standard / Default.
- Drag and drop your offer table from the “Data Sources” box into an empty WPF Window or Page. Note: Do not drop it into an existing DataGrid; it might work, but you might have AutoGenerateColumns enabled afterwards which you might not want, or you would have to create the visible columns manually.
- Now you should be able to see your table columns in the designer, with DateTimePickers already enabled for Date columns etc.
- For the columns on which you want to create a Combobox, enter the DataGrid->Properties->Columns listing, then add a DataGridComboboxColumn.
- Set the properties for (right value equals to WinForms property)
- SelectedValueBinding <=> ValueMember
- DisplayMemberPath <=> DisplayMember
- In XAML, set an x:Name attribute for your DataGrid and the Combobox column, so you can access them directly within your C# code. The column should then look like
<DataGridComboBoxColumn x:Name="colCustomer" SelectedValueBinding="{Binding customerId}" DisplayMemberPath="name" SelectedValuePath="id">
- In .cs file, set
dbEntities db = new dbEntities(); //Your ADO.NET EF dataGrid.ItemsSource = db.offer; //<=> DataSource / Datamember property in WinForms colCustomer.ItemsSource = db.customer;
- Run your project.