locked
How to add record from one datagrid to another datagrid RRS feed

  • Question

  • Hi All.

    I'm using EF in the project . The UI layer has WPF Form1 with GataGrid1 of employees that populated by selected ComboBox department value. Now I would like to call From2 from Form1 with DataGrid2 list of all other employees except employees that not displayed in Form1. The list of DataGrid2 will use to add employee or employees to DataGrid1 of Form1. The DataGrid2 should has ability to select multiple rows. How to create LINQ or lambda query to solve that task?  I will appreciate for detail explanation and sample.

    Thanks.





    • Edited by zleug Sunday, August 30, 2020 1:29 PM
    Sunday, August 30, 2020 5:13 AM

All replies

  • Hi zleug,

    Please see the example below.

    For the sake of simplicity, I did not add combobox, but directly specified the filter conditions. In order to allow the datagrid to detect changes in data, I used ObservableCollection<T> as the item source.

    The code for the first window:

            public ObservableCollection<People> peoples = null;
            public MainWindow()
            {
                InitializeComponent();
                using (var content = new Model1())
                {
                    var collection = content.People.ToList();
                    peoples = new ObservableCollection<People>(collection.Where(peo => peo.DepartmentID==2));
                    dataGrid.ItemsSource = peoples;
                }
            }
    
            private void button_Click(object sender, RoutedEventArgs e)
            {
                Window1 window1 = new Window1();
                window1.Show();
            }

    We can use the checkbox to select rows, but for simplicity, I use Ctrl + left mouse button to select multiple items.

    The code for the second window:

            public Window1()
            {
                InitializeComponent();
                using (var content = new Model1())
                {
                    dataGrid.ItemsSource = content.People.Where(peo => peo.DepartmentID != 2).ToList() ;
                }
            }
            private void button_Click(object sender, RoutedEventArgs e)
            {
                var re = dataGrid.SelectedItems.Cast<People>();
    
                foreach (var item in re)
                {
                    ((MainWindow)Application.Current.MainWindow).peoples.Add(item);
                }
            }

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, September 4, 2020 7:55 AM