I have a data grid on my WPF application window, and the data is bound to an observable collection. In the DataGrid, I have set the property CanUserDeleteRows=True
and I am able to delete the row by pressing the Delete button on the keyboard.
This doesn't look quite intuitive to me. I want to keep an additional column which has delete button on pressing which the row should get deleted. (something like what can be done in ItemTemplate in ASP.NET)
<DataGrid x:Name="dgrQuestions" AutoGenerateColumns="False" Height="224" HorizontalAlignment="Left" Margin="42,73,0,0" VerticalAlignment="Top" Width="663" ItemsSource="{Binding QueList}" CanUserAddRows="True" CanUserDeleteRows="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Qu" Binding="{Binding Path=Que, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="An" Binding="{Binding Path=Ans, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="Hi" Binding="{Binding Path=Hi, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid.Columns>
How to get this functionality of deleting rows by using a button
inside the datagrid itself
You can add a DataGridTemplateColumn
that contains a button that invokes the Delete
command. The DataGrid will handle the Delete command and remove the row.
<DataGridTemplateColumn Header="Actions" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Remove Row" Command="Delete"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
You will have to add DataGridTemplateColumn to your grid. Something like
<DataGrid x:Name="dgrQuestions" AutoGenerateColumns="False" Height="224" HorizontalAlignment="Left" Margin="42,73,0,0" VerticalAlignment="Top" Width="663" ItemsSource="{Binding QueList}" CanUserAddRows="True" CanUserDeleteRows="True">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Delete" Width="75">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Delete" Tag="{Binding}" Click="OnDelete"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Qu" Binding="{Binding Path=Que, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="An" Binding="{Binding Path=Ans, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="Hi" Binding="{Binding Path=Hi, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid.Columns>
Then bind your button to any ID, or item {Binding} and you can handle event in code behind (OnDelete) or you can bind button directly to the command, but then you will need to bind SelecteItem to the ViewModel and deal with it on Command executed:
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
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