I have a WPF DataGrid that I want to be able to Update, Insert and Delete from. I bind to the DataGrid.DataContext with an ObservableCollection.
When the DataGrid’s SelectionChanged() event fires, I perform a Context.SaveChanges() to write back to the database.
However, the above only works when I Update existing records. When I try to add a new record by clicking on the last row in the DG or when I press delete, the SaveChanges() doesn’t do anything. The data is not added or deleted.
How can I add or delete records from a DataGrid? Here is my DG xaml:
<DataGrid AutoGenerateColumns="False" Margin="0,12,0,89" Name="grdContact"
CanUserAddRows="True" SelectionMode="Single" IsReadOnly="False" CanUserDeleteRows="True"
ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True"
Focusable="True"
SelectionChanged="grdContact_SelectionChanged"
<DataGrid.Columns>
<DataGridTextColumn Header="Last Name" Width="150" Binding="{Binding LastName}"/>
<DataGridTextColumn Header="First Name" Width="150" Binding="{Binding FirstName}"/>
</DataGrid.Columns>
</DataGrid>
My Code Behind – Pseudo code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var CustomerObj = new ObservableCollection<Contact>(GetContacts());
grdContact.DataContext = CustomerObj;
}
private void grdContact_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Context.SaveChanges();
}
This is because
ObservableCollection<T>does not notify the context of added or removed items. In fact, it knows nothing about your database context!You’ll have to wire up the
CustomerObjcollection to add or delete objects from the context: