List<T> vs BindingList<T> Advantages/DisAdvantages

C#.NetWinformsData BindingDatagridview

C# Problem Overview


Can someone describe what the difference between the two are for my project.

Currently I 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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonView Question on Stackoverflow
Solution 1 - C#Alex JView Answer on Stackoverflow
Solution 2 - C#Gerrie SchenckView Answer on Stackoverflow