1
votes

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();
    }
2
You might also consider binding directly to an EntityCollection.user7116

2 Answers

2
votes

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 CustomerObj collection to add or delete objects from the context:

CustomerObj.CollectionChanged += CustomerObj_CollectionChanged;
...

private void CustomerObj_CollectionChanged(object sender,
    NotifyCollectionChangedEventArgs e)
{
    switch (e.Action)
    {
        case NotifyCollectionChangedAction.Add:
            foreach (var item in e.NewItems.Cast<Contact>())
                Context.AddObject(item);
            break;
        case NotifyCollectionChangedAction.Remove:
            foreach (var item in e.OldItems.Cast<Contact>())
                Context.DeleteObject(item);
            break;
        // handle Replace, Move, Reset
    }

    Context.SaveChanges();
}
0
votes

I had very similar problem. When getContacts() returned List I was able only to update (not insert or delete). But when getContects returns IQueryable Everything works perfect (but I can't sort :( )