szpic
szpic

Reputation: 4498

Handling changes in ObservableCollection

I have little problem with handling data modifications in my datagridView. I bind a DataSource to the datagridview just like this:

     private void Form1_Load(object sender, EventArgs e)
    {
        var customersQuery = new ObservableCollection<Payment>(context.Payments);
        customersQuery.CollectionChanged += new NotifyCollectionChangedEventHandler(customerQuery_Changed);
        dataGridView1.DataSource = new BindingSource() { DataSource = customersQuery };

    }
    OrdersDataModelContainer context = new OrdersDataModelContainer();

and I'm handling changes like below:

    private void customerQuery_Changed(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach (Payment p in e.NewItems)
            {
                context.Payments.Add(p);
            }
        }
        if (e.Action == NotifyCollectionChangedAction.Remove)
        {
            foreach (Payment p in e.OldItems)
            {

                context.Payments.Remove(p);
            }
        }
        context.SaveChanges();
    }

Remove works but Add not so well. Add action is called when I click on the new row co I'm getting exception because cell are empty. How in simply way I can change behavior to call Add after inserting is over and i switch to next row? Another problem is with modifications of existing data rows. They are updated in database only after inserting new data.

Can anyone give me solution or point where I should search for it?

Upvotes: 1

Views: 305

Answers (2)

Nikita
Nikita

Reputation: 422

On CollectionChanged insert new empty elements. On PropertyChanged insert values to elements.

Upvotes: 1

Georgi-it
Georgi-it

Reputation: 3686

You can use the following class:

public class MyCollection<T> : System.Collections.ObjectModel.ObservableCollection<T>
{
    public event CollectionChangeEventHandler RealCollectionChanged;

    protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        base.OnCollectionChanged(e);
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add && e.NewItems.Count > 0)
        {
            this.OnRealCollectionChanged(e.NewItems[0]);
        }
    }

    protected virtual void OnRealCollectionChanged(object element)
    {
        if (this.RealCollectionChanged != null)
        {
            this.RealCollectionChanged(this, new CollectionChangeEventArgs(CollectionChangeAction.Add, element));
        }
    }
}

This event will be thrown after the standard one, however this is the latest point it can be thrown at.

Upvotes: 1

Related Questions