Datagrid combobox Itemssource not updating

Pratham Jain 221 Reputation points
2023-09-11T11:29:13.27+00:00

Hi All, I have a datagrid in WPF page which is bound to data. In this datagrid I have a combobox column which displays a selected item and list initially for every record. I need to filter the combobox Itemssource whenever user selects it for editing/selection of item for every record. I am implementing this on datagrid.selectionchanged event where the list bound to Itemssource of this combobox in Datagridtemplatecolumn.celltemplate is filtered and filtered list is bound to combobox in celleditingtemplate but combobox still displaying all items without filtering. The Itemssource of combobox is bound to dictionary. Please suggest how to fix this issue ASAP. Regards, Pratham

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,762 questions
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,511 Reputation points Microsoft Vendor
    2023-09-13T06:48:13.5233333+00:00

    Hi,@Pratham Jain. For the problem of filtering the dictionary, you could try to refer to the sample code below.

    Generally, TextBlock is set in DataGridTemplateColumn.CellTemplate. If a ComboBox is set in it, it will overlay the ComboBox of DataGridTemplateColumn.CellEditingTemplate.

    So the comboBox you see with the complete list is in a DataGridTemplateColumn.

    I tested the code in the comments and the filtering was unsuccessful. So I modified the code and it does the filtering.

     <DataGrid Name="dgEmployee" IsReadOnly="False"  CanUserResizeRows="True" CanUserSortColumns="True" ItemsSource="{Binding Path=EmployeeItems}"      
                      HeadersVisibility="Column" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="False" SelectionMode="Single"
                      SelectedItem="{Binding SelectedItem}"  >
                
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Employee Id" Binding="{Binding EmployeeID}"    />
                    <DataGridTemplateColumn Header="Employee Name" MinWidth="120">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding EmployeeName}" />
                                <!--<ComboBox Height="22" Text="{Binding Path=EmployeeName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" x:Name="cmbEmployeeList"
                                          ItemsSource="{Binding DataContext.EmployeeList, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}" 
                                          SelectedValuePath="Value" DisplayMemberPath="Value" IsEnabled="True" IsEditable="True"></ComboBox>-->
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                        <DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <ComboBox Height="22" ItemsSource="{Binding DataContext.FilteredEmployeeList, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}" 
                                            SelectedValuePath="Value" DisplayMemberPath="Value"
                                          SelectedItem="{Binding Path=SelectedEmployee, UpdateSourceTrigger=PropertyChanged}"  IsEnabled="True" IsEditable="True"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellEditingTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>
            </DataGrid>
    

    codebedhind:

    
      public partial class MainWindow : Window        ,INotifyPropertyChanged
        {
            public MainWindow()
            {
                InitializeComponent();
    
                EmployeeItems = new ObservableCollection<EmployeeItem>
                {
                    new EmployeeItem { EmployeeID = 1, EmployeeName = "John" },
                    new EmployeeItem { EmployeeID = 2, EmployeeName = "Jane" },
                    new EmployeeItem { EmployeeID = 3, EmployeeName = "Bob" },
                    new EmployeeItem { EmployeeID = 4, EmployeeName = "Alice" }
                 
                };
    
                EmployeeList = new Dictionary<int, string>
                {
                    { 1, "John" },
                    {  2, "Jane" },
                    { 3, "Bob" },
                    {  4, "Alice" }      ,
                 
                    //{  "8", "lin" }
    
                };
    
                FilteredEmployeeList = new Dictionary<int, string>();
                DataContext = this;
            }
         
            private EmployeeItem selectedItem;
            public EmployeeItem SelectedItem
            {
                get { return selectedItem; }
                set
                {
                    if (selectedItem != value)
                    {
                        selectedItem = value;
                        OnPropertyChanged("SelectedItem");
                        UpdateFilteredDictionary();
                    }
                }
            }
            private void UpdateFilteredDictionary()
            {
              
               
                FilteredEmployeeList = EmployeeList.Where(item => item.Key == SelectedItem.EmployeeID).ToDictionary(item => item.Key, item => item.Value);
               
             
            }
    
    
            private ObservableCollection<EmployeeItem> _employeeItems;
            public ObservableCollection<EmployeeItem> EmployeeItems
            {
                get { return _employeeItems; }
                set
                {
                    _employeeItems = value;
                    OnPropertyChanged(nameof(EmployeeItems));
                }
            }
    
            private Dictionary<int, string> _employeeList;
            public Dictionary<int, string> EmployeeList
            {
                get { return _employeeList; }
                set
                {
                    _employeeList = value;
                    OnPropertyChanged(nameof(EmployeeList));
                }
            }
    
            private Dictionary<int, string> _filteredEmployeeList;
            public Dictionary<int, string> FilteredEmployeeList
            {
                get { return _filteredEmployeeList; }
                set
                {
                    _filteredEmployeeList = value;
                    OnPropertyChanged(nameof(FilteredEmployeeList));
                }
            }
    
    
    
            private void dgEmployee_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                if (e.AddedItems.Count > 0)
                {
                    if (e.AddedItems[0] is EmployeeItem objEmployee)
                    {
                        List<string> employeeNameList = EmployeeItems
                            .Where(employee => employee.EmployeeID == objEmployee.EmployeeID)
                            .Select(emp => emp.EmployeeName)
                            .Distinct()
                            .ToList();
                     
                    }
                }
            }
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string name = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }
        }
    
        public class EmployeeItem
        {
            
                   public int EmployeeID { get; set; }
                   public string EmployeeName { get; set; }
            public KeyValuePair<int, string> SelectedEmployee { get; set; }
        }
    
    
    

    The result:

    8


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.