Tuesday, 26 January 2010

List<T> working with DataGridView

As you all know you can bind a List<T> into a DataGridView in .net 3.5. The DataGridView even automatically allows you to edit the bound List<T> data. But there are still some tips when working with DataGridView. This article is a quick guide to let you know how to make this kind of generic binding working properly even when you programmatically changing the source data.

Case 1: when you edited the data in a bound List<T>, simply call DataGridView.Refresh() to allow you changes be shown. Or you can set the DataSource of the DataGridView to null and reset the DataSource to the List<T>.

Case 2: when you added or removed records from the List<T> then you cannot refresh the DataGridView to see your changes, in this case you have to re-bind the DataSource (by re-bind I mean set the DataSource to null and then set it back to the List<T> otherwise the re-bind will not happen since the DataGridView will think the datasource didn't change)

Case 3: When you directly bind a List<T> to a DataGridView you will find it doesn't allow you adding or deleting record from the UI even you set the AllowUserToAddRows and AllowUserToDeleteRows. To allow you do these things in DataGridView UI we are going to use another Type BindingSource which implemented related interface to allow DataGridView add/edit/delete data from its data source. The sample code:

List<T> data = new List<T>();
BindingSource binding = new BindingSource();
inding.DataSource = data;
DataGridView.DataSource = binding;


Go back to Case 1 and 2, when you are using BindingSource instead of directly use List<T> now you have another way to refresh your DataGridView, BindingSource.ResetBindings(bool) which forces the DataGridView to reread all the items from the List<T> and refresh their displayed values.

No comments: