I have a datagrid with the delete icon as one column and the update icon as another column. When you click update, the first cell is set to focus.
When I click on delete, I want to delete this selected row, but I get the error message "Operation is not valid when using ItemsSource. Instead, select and modify items using ItemsControl.ItemsSource." with the following code:
<DataGrid Name="grdList" Margin="3,16,0,5" RowHeight="30" ColumnWidth="*" ItemsSource="{Binding List,Mode=TwoWay}" Width="434" AutoGenerateColumns="False" CanUserAddRows="False" AlternatingRowBackground="#FFB9BBFF"> <DataGrid.Columns> <DataGridTextColumn MinWidth="0" Header="Property" Binding="{Binding Path=Property}"> </DataGridTextColumn> <DataGridTemplateColumn Header="Update" MinWidth="50" MaxWidth="50"> <DataGridTemplateColumn.CellStyle> <Style TargetType="DataGridCell"> <EventSetter Event="PreviewMouseLeftButtonDown" Handler="EventSetter_OnHandler"></EventSetter> </Style> </DataGridTemplateColumn.CellStyle> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source="Icons/Update.jpg"> </Image> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Delete" MinWidth="50" MaxWidth="50"> <DataGridTemplateColumn.CellStyle> <Style TargetType="DataGridCell"> <EventSetter Event="PreviewMouseLeftButtonDown" Handler="EventSetter_OnHandler"></EventSetter> </Style> </DataGridTemplateColumn.CellStyle> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source="Icons/Delete.jpg"> </Image> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> private void EventSetter_OnHandler(object sender, MouseButtonEventArgs e) { object source = e.OriginalSource; if (source.GetType() == typeof(Image)) { grdList.IsReadOnly = false; selectedRow = FindParent<DataGridRow>(sender as DependencyObject); if (((DataGridCell)sender).Column.Header.ToString().ToUpperInvariant() == "DELETE") { grdList.Items.Remove(selectedRow); } else { DataGridCellsPanel panel = FindVisualChild<DataGridCellsPanel>(selectedRow); DataGridCell dgc = panel.Children[0] as DataGridCell; dgc.Focus(); grdList.BeginEdit(); e.Handled = true; } } }
Also how to add the delete function using the "Delete" key along with clicking on the delete cell.
source share