How I can Delete Selected Row in datagrid wpf?

我怕爱的太早我们不能终老 提交于 2020-01-23 06:53:42

问题


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 ?


回答1:


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.




回答2:


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).




回答3:


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}



回答4:


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.



来源:https://stackoverflow.com/questions/26506901/how-i-can-delete-selected-row-in-datagrid-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!