Select Page
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.

    1. Create an ADO.NET Entity Framework and generate your database tables, e.g. with the wizard.
    2. In the DB model properties, set code generation strategy from None to Standard / Default.
    3. 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.
    4. Now you should be able to see your table columns in the designer, with DateTimePickers already enabled for Date columns etc.
    5. For the columns on which you want to create a Combobox, enter the DataGrid->Properties->Columns listing, then add a DataGridComboboxColumn.
    6. Set the properties for (right value equals to WinForms property)
      • SelectedValueBinding <=> ValueMember
      • DisplayMemberPath <=> DisplayMember
    7. 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">
    8. 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;
      
    9. Run your project.