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 ?
You can access the currently selected item of a DataGrid using the SelectedItem property. After the first line you need to extract the information (e.g. some Id) from the item in order to delete it in the database. Usually you cast the SelectedItem to the object you used to bind to the grid. See also this response.
By default, the user can delete rows by selecting one or more rows and pressing the DELETE key.
WPF DataGrid (SfDataGrid) provides built-in row called AddNewRow. It allows user to add a new row to underlying collection. You can enable or disable by setting SfDataGrid.
In this article, I will show you how to delete selected rows from a GridView in ASP.NET. We are using a checkbox inside a GridView and a button. The User selects the row from the checkbox that he want to delete and on a button click it is deleted from the GridView and from the database too.
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.
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).
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With