List<T> vs BindingList<T> Advantages/DisAdvantages
Can someone describe what the difference between the two are for my project.
Currently I 开发者_JAVA百科have a List<MyClass>
and set the BindingSource to that and a DataGridView to the BindingSource.
I have implemented IEditableObject
so when CancelEdit is called I revert my object back to what it was with a Memberwise.Clone()
Will changing my List to a BindingList solve any of this and what are the advantages of using a BindingList?
A List<>
is simply an automatically resizing array, of items of a given type, with a couple of helper functions (eg: sort). It's just the data, and you're likely to use it to run operations on a set of objects in your model.
A BindingList<>
is a wrapper around a typed list or a collection, which implements the IBindingList
interface. This is one of the standard interfaces that support two-way databinding. It works by implementing the ListChanged
event, which is raised when you add, remove, or set items. Bound controls listen to this event in order to know when to refresh their display.
When you set a BindingSource's DataSource to a List<>
, it internally creates a BindingList<>
to wrap your list. You may want to pre-wrap your list with a BindingList<>
yourself if you want to access it outside of the BindingSource, but otherwise it's just the same. You can also inherit from BindingList<>
to implement special behavior when changing items.
IEditableObject
is handled by the BindingSource. It'll call BeginEdit on any implementing object when you change the data in any bound control. You can then call EndEdit/CancelEdit on the BindingSource and it will pass it along to your object. Moving to a different row will call EndEdit as well.
A BindingList allows two-way databinding by using events, a List does not fire events when its collection changes.
I don't think it will fix your particular problem.
精彩评论