简体   繁体   中英

Binding List<T> with datagridview in C#

I would like to know what is the difference between binding list directly to datagridview datasource and binding Bindingsource to datagridview. Here is example:

Ex1:

List<Employee> list = this.GetEmployees();
dgvEmployees.Datasource = list;

Ex2:

List<Employee> list = this.GetEmployees();
BindingSource soure = new BindingSource();
soure.Datasource = list;
dgvEmployees.Datasource = soure;

So, which one should be the good practice?

In general, using Datasource directly is for simple cases and using a BindingSource is for more complex cases. When all you want to do is display data and don't really care about modifying it before it's displayed, feel free to use Datasource

BindingSource on the other hand, allows you to (not an exhaustive list):

  • Specify a Format method to transform the list data before the user sees it, and a Parse method to transform the list data back after the user edits it
  • Track the Current (selected) item in the list
  • Customize the way a new element is added
  • Prevent edits to the current item
  • Be notified when an element is added or removed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM