BindingSource - What are the Benefits of Using BindingSource

Which gives me something like this:

DataGridView dgvDocuments = new DataGridView(); BindingSource bindingSource = new BindingSource(); DataTable dtDocuments; dtDocuments = MsSQL.GetDocuments(dtpOd.Value, dtpDo.Value); bindingSource.DataSource = dtDocuments; dgvDocuments.DataSource = bindingSource; 

instead of this:

 DataGridView dgvDocuments = new DataGridView(); DataTable dtDocuments; dtDocuments = MsSQL.GetDocuments(dtpOd.Value, dtpDo.Value); dgvDocuments.DataSource = dtDocuments; 
+6
source share
2 answers

BindingSource have many advantages, below some of them

1) When you bind data to any control using bindingsource, it will act on both sides. Any changes made to the effects of the data source for control and any changes to the data source of the control effects. You do not need to take the value from the control and assign it to the data source again

2) You can apply filter to datasource using BindingSource

3) You can work with one datasource tied to many controls . For example, you have a Fruits table, and you bind this table to 2 DataGridView to display Aplles and Peaches separately. Using the BindingSource filter property, you can display Apples and Peaches separately.

4) You can search, sort, edit, filter using the binding source

You cannot see the benefits of binding for main lists, but there is more than a main list that you will see how useful it is to use bindingsource.

You can get more information here.

+1
source

One of the benefits is that if you manually manipulate the values ​​in the DataGridView, the changes will be reflected in the underlying data. (EDIT: obviously this also works with a regular DataSource binding.)

Another advantage is that you get the opportunity to add an entry to the underlying data (at least if it is a List ) by clicking on an extra empty field and editing the values. This will add a new item without any additional code to write.

enter image description here

This detailed data binding guide can help shed more light on data binding capabilities in general.

EDIT:

Another difference is that manipulation of the underlying data, for example adding an item to the list, will not be displayed in the DataGridView , even if you again set the DataSource property, which will work, for example, in ComboBox . But reassigning a new instance of BindingSource will do the trick.

So, if you have a List of Faces:

 List<pers> list = new List<pers>(); BindingSource bs = new BindingSource(); bs.DataSource = perlist; dataGridView1.DataSource = bs; 

and then you want to add a new element to the list in the code, just create a new instance of BindingSource , reassign it to DataGridView.DataSource

 list.Add(new pers()); bs = new BindingSource(); bs.DataSource = perlist; dataGridView1.DataSource = bs; 

and the new item will be displayed

+3
source

Source: https://habr.com/ru/post/1014593/


All Articles