Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a row in WPF DataGrid

Tags:

c#

wpf

datagrid

I have a datagrid with a delete icon as one column and update icon as another column. On click of update, the first cell is set on focus.

On click on delete I want to delete that selected row, but I get the error "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead." with the following code:

XAML:

<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}"/>

        <DataGridTemplateColumn Header="Update"  MinWidth="50" MaxWidth="50">
            <DataGridTemplateColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <EventSetter Event="PreviewMouseLeftButtonDown"
                                 Handler="EventSetter_OnHandler"/>
                </Style>
            </DataGridTemplateColumn.CellStyle>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="Icons/Update.jpg"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="Delete"  MinWidth="50" MaxWidth="50">
            <DataGridTemplateColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <EventSetter Event="PreviewMouseLeftButtonDown"
                                 Handler="EventSetter_OnHandler"/>
                </Style>
            </DataGridTemplateColumn.CellStyle>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="Icons/Delete.jpg"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

C#:

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 with the "Delete" key together with the click on the delete cell.

like image 466
user2480288 Avatar asked Jul 01 '14 19:07

user2480288


People also ask

How do I delete a row in data grid?

Right click and delete row from datagridview After retrieveing the row index, next step is to delete the specified row. In the contextMenuStrip1_Click event delete the row using rowindex value.

Can user delete rows WPF?

By default, the user can delete rows by selecting one or more rows and pressing the DELETE key. Deleting a row removes the item that the row represents from the ItemsSource. If the ItemsSource does not allow deletions, the user cannot delete rows even if this property is set to true .

How do I delete a row in react data grid?

Adding and Removing Rows (React)allowDelete: Setting this property to true causes the grid to remove selected rows when the user presses the 'Delete' key. newRowAtTop: Setting this property to true causes the grid to show the new row template at the top of the grid rather than the bottom.

How to add row in DataGrid wpf?

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. AddNewRowPosition property.


1 Answers

I suspect on Delete i.e. in EventSetter_OnHandler, you must be removing items from the Items collection of dataGrid. Something like this:

grdList.Items.Remove(someItem);

But as the error is self explanatory

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

You have binded ItemsSource to some collection, so you need to remove item from it. You can't modify the Items collection directly when binding ItemsSource with some collection. It should be something like:

List.Remove(someItem);
like image 187
Rohit Vats Avatar answered Sep 21 '22 12:09

Rohit Vats