Sunday, 11 January 2015

Binding a DataGridView to a Collection - Notify Grid When Properties are Changed (BindingList and INotifyPropertyChanged)

When utilising a DataGridView or similar control within your windows and web applications, you may wish to bind to a collection (List, ArrayList etc). Binding is always great as you can maintain and manage your custom objects very easily. What can be tough to manage is when you may wish to edit the controls data (A cells contents within a DataGridView for example), so you have to edit the data within your data source (I.e. List of custom objects), then re-bind to reflect the new changes.

The method above would work, but utilising a more Observer Pattern approach to our programming, we can automatically notify the grid when we update any of our properties within our custom collection. You simply need to inherit from INotifyPropertyChanged within your custom object and bind to a DataGridView with a BindingList collection (Very similar to a List). Within the set properties for your custom object, simply raise an event.

A full example can be found here: http://tech.pro/tutorial/776/csharp-tutorial-binding-a-datagridview-to-a-collection

No comments: