Why Default Value of DataGridComboBoxColumn does not appear in the DataGrid in C# WPF?

Mojtaba_Hakim 321 Reputation points
2023-05-02T20:03:51.4133333+00:00

Project subject: I had an MS Access 2003 adp VBA project that would connect to SQL Server Database, Now I'm converting that project to C# WPF, and I'm going to save data directly into SQL Server database from DataGrid in C# WPF

Detail: I have DataGrid that ItemsSource binds to an 'ObservableCollection' named: 'INVO_DATA_RASID_KHARID' and also 'DataGridComboBoxColumn' named: 'ANBAR_COLUMN' the 'ItemSource' of this 'DataGridComboBoxColumn' is filled through SQL Server.

I want this 'DataGridComboBoxColumn' to be displayed with a default value so that the user knows that there is no need to manually select it from the 'DataGridComboBoxColumn' list.

I set this default value through a static variable in code behind in this method named: 'FillALLComboboxes'.

DataGridComboBoxColumn

The Problem: Considering that 'DataGridComboBoxColumn' in the DataGrid, the 'ANBAR_COL' 'DataGridComboBoxColumn' has a default value, the user does not need to select that item manually from the 'DataGridComboBoxColumn' list, but as long as they double-click on the 'ANBAR_COL' combobox cell, the default value It will appear! The point is that the default value set for 'DataGridComboBoxColumn' will not be displayed until the user enters the cell!

Anbar

XAML :

     <DataGrid   x:Name="INVO_LST_RASID_SUB"
                        EnableColumnVirtualization="True"
                        EnableRowVirtualization="True"
                        VirtualizingPanel.IsVirtualizing="True"
                        VirtualizingPanel.VirtualizationMode="Recycling"
                        ScrollViewer.CanContentScroll="False"
                    
                        KeyboardNavigation.TabNavigation="Contained"
                        ItemsSource="{Binding INVO_DATA_RASID_KHARID}"
                        Grid.Row="5"
                        Margin="5,10"
                        AutoGenerateColumns="False"  FlowDirection="RightToLeft"  SelectionUnit="FullRow"   BorderThickness="1" >
       
            <DataGrid.Columns>
                <DataGridComboBoxColumn x:Name="ANBAR_COLUMN" MinWidth="80" Width="auto" Header=" انبار " 
                                        SelectedValueBinding="{Binding ANBAR,UpdateSourceTrigger=PropertyChanged}"
                                        DisplayMemberPath="NAMES" SelectedValuePath="CODE">
                    <DataGridComboBoxColumn.EditingElementStyle>
                        <Style TargetType="{x:Type ComboBox}">
                            <Setter Property="IsEditable" Value="True"/>
                        </Style>
                    </DataGridComboBoxColumn.EditingElementStyle>
                </DataGridComboBoxColumn>
       
            </DataGrid.Columns>
        </DataGrid>

C#:

Code behind of my Window (C#):

//MainWindow:
    public partial class HEAD_LST_RASID : Window
    {
        public ObservableCollection<INVO_LST_RASID_KHARID_CSHARP> INVO_DATA_RASID_KHARID { get; set; } = new ObservableCollection<INVO_LST_RASID_KHARID_CSHARP>();

        public HEAD_LST_RASID()
        {
            InitializeComponent();
            this.DataContext = this;
        }
        public void FillALLComboboxes()
        {
            string RowSource_ANBAR = "SELECT    CODE, NAMES FROM  dbo.TCOD_ANBAR";
            //Search for the default value if it exists
            var rst = dbms.Database.SqlQuery<int?>("SELECT     ANBCO FROM dbo.OPANBACCESS WHERE     (USERCO = " + Baseknow.USERCOD + " ) ORDER BY dbo.OPANBACCESS.RDF").ToList();
            if (rst.Count > 0)
            {
                Baseknow.anbardef = (int)rst.FirstOrDefault();
            }
            var ARST = dbms.Database.SqlQuery<Custom_TCODANBAR>(RowSource_ANBAR).ToList();
            ANBAR_COLUMN.ItemsSource = ARST;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            FillALLComboboxes();
            
              var QRE_LST = dbms.Database.SqlQuery<INVO_LST_RASID_KHARID_CSHARP>($@"SELECT * FROM INVOICES").ToList();
              INVO_DATA_RASID_KHARID?.Clear();
              
                foreach (var item in QRE_LST)
                    INVO_DATA_RASID_KHARID.Add(item);
        }
    }
Model Class :

//Model:
    public class CTABLES
    {
        public class INVO_LST_RASID_KHARID_CSHARP : INotifyPropertyChanged, ICloneable
        {
            public object Clone()
            {
                return this.MemberwiseClone();
            }
        
            public INVO_LST_RASID_KHARID_CSHARP()
            {
                ANBAR = Baseknow.anbardef;
            }

            private int? _anbar;
            public int? ANBAR
            {
                get
                {
                    return _anbar;
                }
                set
                {
                    if (_anbar == value)
                        return;
                    _anbar = value;
                    OnPropertyChanged("ANBAR");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            protected virtual void OnPropertyChanged(string propertyName = "")
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

What I want is to show that a default value has been selected for this combobox inside the 'DataGrid' when the 'DataGrid' data is loaded (without the need to double-click and go to CellEditing mode).

Developer technologies Windows Presentation Foundation
Developer technologies .NET Other
Developer technologies Visual Studio Other
{count} votes

1 answer

Sort by: Most helpful
  1. Hui Liu-MSFT 48,676 Reputation points Microsoft External Staff
    2023-05-08T08:58:48.27+00:00

    Hi,@Mojtaba_Hakim.

    It can successfully display the default value of the setting without double-clicking. The following sample results can be displayed more clearly.

    The DataGrid displays the existing data in the collection, and does not display the data that has not been added.

    In my example above, the data that exists in the first row does not need to be clicked to display its value. For the new data that needs to be added, it is necessary to click or other actions to add a new item to display the value of the new item.

    I add code CanUserAddRows="True" in DataGrid and added a property to the object for testing.

     <DataGrid  
    
             ...
    
     CanUserAddRows="True">
    
     <DataGrid.Columns>
                    <DataGridComboBoxColumn x:Name="ANBAR_COLUMN" MinWidth="80" Width="auto" Header=" انبار " 
                                            SelectedValueBinding="{Binding ANBAR,UpdateSourceTrigger=PropertyChanged}"
                                           
                                            DisplayMemberPath="NAMES" SelectedValuePath="CODE">
                        <DataGridComboBoxColumn.EditingElementStyle>
                            <Style TargetType="{x:Type ComboBox}">
                                <Setter Property="IsEditable" Value="True"/>
                            </Style>
                        </DataGridComboBoxColumn.EditingElementStyle>
                    </DataGridComboBoxColumn>
                    <DataGridTextColumn Header="test" Binding="{Binding Test,UpdateSourceTrigger=PropertyChanged}"/>
                </DataGrid.Columns>
            </DataGrid>
    

    Codebedhind:

    private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                FillALLComboboxes();
                List<INVO_LST_RASID_KHARID_CSHARP> QRE_LST = new List<INVO_LST_RASID_KHARID_CSHARP>();
                QRE_LST.Add(new INVO_LST_RASID_KHARID_CSHARP() { Test="test1"});
                INVO_DATA_RASID_KHARID?.Clear();
    
                foreach (var item in QRE_LST)
                    INVO_DATA_RASID_KHARID.Add(item);
            }
    
     public class INVO_LST_RASID_KHARID_CSHARP : INotifyPropertyChanged, ICloneable
            {
               ...
            private string test;
            public string Test
            {
                get
                {
                    return test;
                }
                set
                {
                    if (test == value)
                        return;
                    test = value;
                    OnPropertyChanged("Test");
                }
            }
          
            }
        
    
    

    The result:

    9


    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.


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.