surpavan
surpavan

Reputation: 1412

Observable Collection is not updating the datagrid

I am using a Dim All_PriceLists As System.Collections.ObjectModel.ObservableCollection(Of BSPLib.PriceLists.PriceListPrime) where PriceListPrime implements Inotify for all properties in it.

I bound the All_PriceList to a datagrid as DataGrid1.ItemsSource = All_PriceLists but when I do All_PriceLists=Getall() where Getall reads and gets the data from the DB, the datagrid is not updating.

It updates only when I hack it this way:

DataGrid1.ItemsSource = Nothing
DataGrid1.ItemsSource = All_PriceLists

Could you please tell me where I have gone wrong or what I should implement. Thank you.

Upvotes: 3

Views: 5305

Answers (3)

Phil
Phil

Reputation: 42991

You have several solutions to your problem

  • Update the ItemsSource directly (instead of replacing the local member variable)

    DataGrid1.ItemsSource = new ObservableCollection(Of PriceListPrime)(GetAll())
    
  • Update the ObservableCollection (as mentioned in another answer)

    All_PriceList.Clear(); 
    For Each item in Getall() 
        All_PriceList.Add(item) 
    Next 
    
  • Set your DataContext to a view model and bind to a property of the view model

    Dim vm as new MyViewModel()
    DataContext = vm
    vm.Items = new ObservableCollection(Of PriceListPrime)(GetAll())        
    

    The view model will implement INotifyPropertyChanged and raised the PropertyChanged event when the Items property is changed. In the Xaml your DataGrid's ItemsSource will bind to the Items property.

Upvotes: 4

Sergei B.
Sergei B.

Reputation: 3227

You should update ObservableCollection instead of creating new one if you want the app to react on your changes.

So, clear All_PriceList collection and add new items into it. Example:

All_PriceList.Clear();
For Each item in Getall()
  All_PriceList.Add(item)
Next

ObservableCollection doesn't support AddRange, so you have to add items one by one or implement INotifyCollectionChanged in your own collection.

Upvotes: 2

user694833
user694833

Reputation:

The problem is that you are not updating the collection, you are replacing it, which is different. The datagrid remains bound to the old list and the updated data is stored in a new unbound collection. So, you are not hacking a solution, your are binding the datagrid to the new collection, which is correct.

If you want a more automatic solution, you should bind your datagrid to a dataset/datatable, which is totally different code.

Upvotes: 2

Related Questions