Winforms – Why use List instead of DataTable for GridControl

Tram Ho

Before I started coding, I used DataTable according to available projects. Later, I felt that DataTable had some disadvantages, so I found another way to optimize. Another reason is that I often handle grid input forms. To speed up the form creation process, it is necessary to design the code so that it is easy to copy, paste and edit (just change the name, type of data fields), not waste time Design the interface. Here I will give the reason and how to solve the problems that I have encountered. If you have any way, please ask for advice.

For example I have 1 BindingList and 1 DataTable

1) Using Linq is easier

2) Limit spelling errors when transmitting FieldName string

  • I use dynamic column creation of gridView when assigning DataSource. So in case you need to access any 1 Cell of the grid, you will use the nameof () method of C # 6.0. For example:

  • In addition, when you need to change the name of 1 Column on the Database, on the Code you also need to change it by => If you use the FieldName string, the Find and Replace is quite inconvenient. Conversely, if you use List, you just need to rename the Model class and let Visual Studio refactor the guys involved

3) Use Data Annotation to set the column

  • No need to open the design on the interface or write code. Using DataAnnotation will help us to quickly solve Format problems on grid

4) 2-way Binding with INotifyPropertyChanged and PropertyChanged.Fody library

  • When we want to change a cell on the grid, we usually have to use:

  • So when changing under DataSource BindingList <Sample>, how will the data on the grid change?

  • Even though the DataSource has changed, the data on the grid remains the same. If you want the grid to update, you must use:

  • I want when there are changes under DataSource, the grid will always change, not need to refresh data => Use INotifyPropertyChanged and PropertyChanged.Fody

  • Fody library automatically add property notification for all classes that execute INotifyPropertyChanged => When there is any change on BindingList <Sample>, gridControl will receive notification and automatically update new data seen on grid.

5) Use MVP pattern

On Presenter, it is easier to process logic and computation using object class. It is also easier to write Unit Test

Share the news now

Source : Viblo