How can I delete the selected row in datagrid wpf?

I am using a WPat datagrid I need to delete the selected row, my code

private void dataGridView1_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Delete) { this.dataGridView1.Items.Remove(this.dataGridView1.SelectedItem); } } 

But when I use this code I will show me an error

Operation is not valid while using ItemsSource. Access and change items with ItemsControl.ItemsSource instead

How can I delete the selected row?

+5
source share
4 answers

You never need to remove a row from a WPF grid. What you need to do:

1) define a type with the ObservableCollection attribute, which contains a list of objects representing the values ​​in your grid.

2) Bind this property to grid control.

3) now, if you add / remove objects from the linked collection, the corresponding lines respectively add / remove from the ui control.

+6
source

I think you are using itemSource to populate dataGridview. Remove the item from the data source and update the binding.

Or your datasource class inherits from INotifyPropertyChanged and raises the PropertyChanged event, and in the XAML list sets UpdateSourceTrigger as the PropertyChanged event, for example below:

 ItemsSource="{Binding MyListItems, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged} 
+2
source

It is assumed that your DataGrid is bound to an ItemsSource element (e.g. ObservableCollection). In this case, manipulating the ItemsSource from the view is unacceptable, and you probably need to delete it in the ViewModel (where the related objects are stored).

+2
source

As the error description clearly states for the user interface control associated with the data source, you must control the data source itself, not the user interface control (in this case, your data network).

The user interface control is just a way of representing your data in the user interface, to display edited or new or changed data (for example, 1 row less), you just need to act in the underlying data source that you assigned the DataGrid ItemSource property.

+1
source

Source: https://habr.com/ru/post/1205268/


All Articles