Home > Net >  Getting data in List into DataGrid ComboBox
Getting data in List into DataGrid ComboBox

Time:11-20

I am having trouble getting items from a list to a combobox column in a datagrid in WPF. This is new to me so any help would be greatly appreciated. It seems there are many ways to do it but I haven't been able to get any of them to work.

'''

                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Positionname}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>

                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox x:Name="poscombo Loaded="comboposloaded"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            
            </DataGridTemplateColumn>

List with Data in the code behind

 List<Positions> PositionList = new List<Positions>();

UPDATE: I ended up adding a loading event to pull the list as the itemsource. The question now is how to get the selected value from combobox back into the text block?

C# Added to get combo loaded.

    private void comboposloaded(object sender, RoutedEventArgs e)
    {
        ComboBox cmb = (ComboBox)sender;
        cmb.ItemsSource = PositionList;
        cmb.DisplayMemberPath = "info";
        cmb.SelectedValuePath = "psnme";

    }

CodePudding user response:

The data binding for DataGridComboBoxColumn looks a little more complicated than you might think.

  1. Use ObservableCollection instead of List. This will automatically update the content of the DataGrid.
  2. You can load data into a combo box using ObjectDataProvide. This will also ensure that the data in the source is automatically updated. Here's a working example.
    public partial class MainWindow : Window
    {
        public EmployeeViewModel EmployeeVM;
        public MainWindow()
        {
            InitializeComponent();
            EmployeeVM = new EmployeeViewModel();
            MyDataGrid.ItemsSource = EmployeeVM.EmployeeList;
        }
    }

    public class Employee
    {
        public string Name { get; set; }
        public PositionEnum Position { get; set; }
    }

    public enum PositionEnum { Marketeer, Mechanic, Accountant };
    public class EmployeeViewModel 
    {
        public ObservableCollection<Employee> EmployeeList =
          new ObservableCollection<Employee>();
        public EmployeeViewModel()
        { 
            EmployeeList.Add(new Employee()
             { Name = "James Smith", Position = PositionEnum.Accountant });
            EmployeeList.Add(new Employee()
             { Name = "Robert Johnson", Position = PositionEnum.Marketeer });
            EmployeeList.Add(new Employee() 
             { Name = "David Williams", Position = PositionEnum.Mechanic });
        }
    }

XAML

<Window x:Class="WpfApp6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:core="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApp6"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" >
    <Window.Resources>
        <!--Create list of enumeration values-->
        <ObjectDataProvider x:Key="myEnum" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local:PositionEnum"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="MyDataGrid"
            AutoGenerateColumns="False"      
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            RowHeaderWidth="0" >
            <DataGrid.Columns>
                <DataGridTextColumn
                   Binding="{Binding Name}"
                   Header="Name" />
                <DataGridComboBoxColumn
                    Header="Order Status"
                    SelectedItemBinding="{Binding Position}"
                    ItemsSource="{Binding Source={StaticResource myEnum}}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

enter image description here

Think you need to familiarize yourself with the MVVM pattern and use that as a basis for building such applications.

CodePudding user response:

The question now is how to get the selected value from combobox back into the text block?

Bind the psnme property of the Positions object to the Positionname property of the data object:

<ComboBox x:Name="poscombo" Loaded="comboposloaded"
          SelectedValue="{Binding Positionname, UpdateSourceTrigger=PropertyChanged}"/>
  • Related