Search code examples
c#winformsdata-bindingcollectionsbindingsource

Updating of BindingSource in WinForms does not update Datasource Collection


I want to display a custom collection in a DataGridView in a Windows Forms app. This custom collection implements ICollection, and IEnumerable. I have set up a BindingSource, using the collection as the .DataSource property. The DataGridView is set to use my BindingSource as it's DataSource. When I add a new item to the collection using the BindingSource.Add() method, the DataGridView updates correctly with the new item. The BindingSource DataSource, on the other hand, does not:

MyCustomCollection myCollection = new MyCustomCollection();

myCollection.Add(myCustomObject1);
myCollection.Add(myCustomObject2);

myBindingSource.DataSource(myCollection);
myBindingSource.Add(myCustomObject3);

In the above code, myBindingSource's internal List contains the right number of records (3), and the DataGridView also contains three records, but myCollection contains only two records. I know that changing the underlying myCollection will NOT update the BindingSource or the DataGridView, as it is not a BindingList<T>, but I was under the impression that updating a BindingSource directly would ensure that myCollection was updated at the same time.

Is there a way to use a collection that isn't a BindingList<T> and have it updated when interacting with the BindingSource directly?

Update: One way I've gotten the data updated across all the parts (Collection, BindingSource, DataGridView) is as follows:

myCollection.Add(myCustomObject3);
myBindingSource.DataSource = null;
myBindingSource.DataSource = myCollection;

I'm pretty sure there's a better way to attack this problem, but this is the only method that's generated the results I was expecting.


Solution

  • The problem is Fill Adaptor. When you load your form, the Fill is done for you. Just make sure to do a Refill and then follow up with Reset bindings post any data changes and Grid will get refreshed.

    Example :

    WorkTableAdapter.Insert(objData.XAttribute, "",
      objData.YAttribute,objLoanData.Amount_IsValid, DateTime.Now, DateTime.Now);
    this.WorkTableAdapter.Fill(this.POCDataSet.Work);
    this.WorkBindingSource.ResetBindings(false);