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.
To connect a DataGridView control to data: Implement a method to handle the details of retrieving the data. The following code example implements a GetData method that initializes a SqlDataAdapter, and uses it to populate a DataTable. It then binds the DataTable to the BindingSource.
The BindingSource component acts as an intermediary that provides binding and currency management services. At design time or run time, you can bind a BindingSource component to a complex data source by setting its DataSource and DataMember properties to the database and table, respectively.
Complex data binding. The ability of a control to bind to more than one data element, typically more than one record in a database. Complex binding is also called list-based binding. Examples of controls that support complex binding are the DataGridView, ListBox, and ComboBox controls.
ObservableCollection<T>
won't work for a DataGridView
: it implements INotifyCollectionChanged
, not IBindingList
, and the DataGridView
doesn't know about INotifyCollectionChanged
. 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 capabilityThe 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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With