C# – What are the benefits of using a bindingsource with bindinglist as datasource

bindinglistbindingsourcecnetwinforms

I can directly bind my DataGridView control to a bindinglist of my business objects by setting the DataSource property. My business object implements INotifyPropertyChanged, so the DGV gets updated when a new item is added to the Binding List or existing one is updated.

With respect to dealing with single records, I can bind my business object to textboxes and other relevant controls.

I can also derive from BindingList and create a CustomBindingList class to implement required methods of IBindable, as explained in the link below :
http://msdn.microsoft.com/en-us/library/aa480736.aspx

Alternatively, I have seen people recommend using a BindingSource. BindingSource's Datasource is the business object and the DGV's DataSource is the BindingSource.

In any case, basing it on a BindingSource does not offer me:

  1. Filtering (Filter does not work). Implementation needs to be provided by me.
  2. Sort and Search does not work. Implementation needs to be provided by me.

So, Why is the BindingSource approach recommended?

Broader Picture:
Am new to OOPS concepts and C#. Working with Database applications. Winforms. So far have only used DataSet / DataTable approach. Now trying to create and use my own custom classes.

Typically have a Master/Detail form. When I click on a Detail row in the DGV, I want to edit that record in a separate window. So I need to get a handle on the list item represented by that row in the DGV. Trying to find a solution for that has brought me to this point and this doubt.

Given what I want to do, which approach is better and why?

Some pointers here would really help as I am very new to this.

Best Answer

It is recommended to use a BindingSource when multiple controls on the form use the same datasource (Behind the Scenes: Improvements to Windows Forms Data Binding)

Design-time: I personally find the BindingSource very helpfull when choosing the properties from my business object when databinding to controls.

To get a handle to the currently selected row, try bindingSource1.Current as MyBusinessObject;

As for filtering and searching: I use a third party dll for grids that have that implemented. So can't help you with that, sorry.

When you work with lists of different types of business objects, don't use the list directly

List<IAnimal> animals = new List<IAnimal>();
animals.Add(new Cat());
animals.Add(new Dog());
bindingSource1.DataSource = animals;

Instead use a BindingList like this:

bindingSource1.DataSource = new BindingList<IAnimal>(animals);

That will make sure all accessed objects in the list are of type IAnimal and saves you some exceptions.

Related Topic