What would be the best collection to use when binding a list of data to a DataGridview in C#? I'm currently using just a Generic List but the data grid doesn't update when there is objects added or removed from the list. I've looked at using a BindingList or a ObservableCollection, but can't decide which would be best to use that would update and be easy to sort/filter without having to rebind to the data grid. I'm currently working in windows form on .Net 3.5 framework with plans to move over to WPF soon.
A DataTable, perhaps?
Also, you can often force the gridview to repaint and include the new items by calling DataGridview.Invalidate() immediately after items are added.
I do not think there's a hard/general rule of what type of collection is best suited for DataGridView.
It really depends on a several factors:
- The nature of the data
- What are the operations (if any) to be performed from the UI to the DB (e.g. CRUD, sort, filter)
- Size of the data
etc etc..
I created my own collection inheriting from BindingList which supports sorting, filtering, etc. It works well now but was a lot of work, I don't really recommend doing one yourself... I think there's one already implemented on CodeProject or a similar site, I'll give you the link if I find it.
Edit:
I found this CodeProject article with an implementation of IBindingList which supports sorting, filtering, etc. I didn't test it though, so I don't know how good the implementation is, but it might be worth checking it out.
The data binding framework is completely different between WinForms and WPF, so (in general), there isn't a "best choice" for the both of them.
For WinForms, using the generic BindingList<T>
will accomplish most of what you want (though it doesn't handle changes to individual items; you'll have to implement that yourself).
For WPF, ObservableCollection<T>
serves a similar purpose.
ObservableCollection<T>
won't work for aDataGridView
: it implementsINotifyCollectionChanged
, notIBindingList
, and theDataGridView
doesn't know aboutINotifyCollectionChanged
. It is intended for WPF bindings and is not used in Windows FormsBindingList<T>
is a good option, but note that it doesn't support sorting or filtering out of the box. However, you can find some custom implementations of these features on the web.DataTable
is probably your best option if you need sorting and/or filtering capability
Actually Microsoft reccomends using a Collection as your binding collection rather than a List because of the ability to do automatic functions like when adding and removing items, clearing the collection, or setting the value of an existing item.
Collection Class on MSDN.
If you want to bind a collection to a datagridview, I'd use a bindinglist. Although a bindinglist does not support sorting out of the box you can extend it by creating your own list that derives from BindinList and implement your own sorting.
See here on how to do this.