K
K
kodwi2015-05-25 11:41:52
WPF
kodwi, 2015-05-25 11:41:52

DataGridComboBoxColumn - how to bind a field from one table for display, and a field from another - for value?

There is a database, there is a DataGrid, there are 2 tables connected by 1 to no. It is necessary that the data from one table is displayed in the grid, and in one of the fields of the grid there is a ComboBox that contains all the related values ​​of a certain column from another table. For example, the first table is Calendar, it has the Day of the week field, which contains the id of the day from the Days of the week table. It is necessary that in the grid in each record in the Day of the week field, not one id is displayed, but a combobox of the names of the days of the week, but when another day is selected, the id in the record changes (i.e. visually in the combobox the names of the days, but in fact their id ).
Can I have a XAML example?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2015-05-25
@Nipheris

So, let's go in order.
1. To begin with, let's assume that you use some kind of ORM, or write SQL queries yourself and convert the results into sane business objects.
2. Let's say you have the CalendarItem and DayOfWeek classes like this:

class CalendarItem
{
    ....
    public string DayOfWeek Day { get; set; }
    public string Text { get; set; }
}

class DayOfWeek
{
    ....
    public int Id { get; }
    public string Name { get; }
}

3. Now we make a datagrid with a combobox. Let's say you have ObservableCollection<CalendarItem> Items. Then you need to bind the grid to this collection, the combobox (its selected value) to the Day property of the calendar element, and what will be displayed in the combo as text to the Description property of the DayOfWeek class. Approximately it will be like this:
<DataGrid x:Name="dataGrid1" CanUserAddRows="False" CanUserDeleteRows="False" AutoGenerateColumns="False" ItemsSource="{Binding Path=Items}">
    <DataGrid.Columns>
        <DataGridComboBoxColumn x:Name="dayColumn" Header="День недели" Width="200" SortMemberPath="Day.Id" DisplayMemberPath="Description" SelectedValueBinding="{Binding Path=Day}" />
        <DataGridTextColumn x:Name="textColumn" Header="Описание события" Binding="{Binding Path=Text}" />
    </DataGrid.Columns>
</DataGrid>

Along with sorting by ID.
Try it all, if something is not clear - in the comments, we'll figure it out. For now, try it without reading from the database, to make it easier, just create objects for the days of the week and some CalendarItems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question