Mahmoud Kassem
Mahmoud Kassem

Reputation: 101

How I can Delete Selected Row in datagrid wpf?

I am using WPF datagrid I need to delete selected Row , my code is

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

But when I using this code show me error

Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead

How I can Delete Selected Row ?

Upvotes: 5

Views: 10986

Answers (4)

Brad
Brad

Reputation: 572

I think you are using a itemSource to populate the dataGridview. Remove the item from the datasource and then refresh the binding.

Or have your datasource class inherit from INotifyPropertyChanged and raise a PropertyChanged event and on the listbox XAML set the UpdateSourceTrigger as the PropertyChanged event, such as below:

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

Upvotes: 2

Dennis Kassel
Dennis Kassel

Reputation: 2786

Is guess your DataGrid is bound to an ItemsSource (e.g. an ObservableCollection). In that case manipulating the ItemsSource from the View is not allowed and you rather have to remove it in the ViewModel (that is where your bound objects are stored).

Upvotes: 2

Tigran
Tigran

Reputation: 62248

You never have to delete the row from the WPF grid. What you have to do is:

1) define a type with a ObservableCollection property that contains a list of objects presenting the values on your grid.

2) Bind that property to your grid control.

3) now if you add/remove objects from binded collection, corresponding rows will respectively add/remove from control's ui.

Upvotes: 6

Davide Piras
Davide Piras

Reputation: 44595

As clearly mentioned in the error description for a UI control bound to a DataSource you should be manipulating the data source itself and not the UI control ( in this case your data grid ).

The UI Control is only a way to present your data in the User Interface, to show edited or new or modified data ( for example 1 row less ) you should simply act on the underlying data source you have assigned to the DataGrid's ItemSource property.

Upvotes: 1

Related Questions