List of <T> Bindings to DataGridView in WinForm
I have a class
class Person{ public string Name {get; set;} public string Surname {get; set;} } and a List<Person> , to which I add some elements. The list is bound to my DataGridView .
List<Person> persons = new List<Person>(); persons.Add(new Person(){Name="Joe", Surname="Black"}); persons.Add(new Person(){Name="Misha", Surname="Kozlov"}); myGrid.DataSource = persons; No problems. myGrid displays two rows, but when I add new items to the persons list, myGrid does not show a new updated list. It shows only two lines that I added earlier.
So what is the problem?
Re-binding works well every time. But when I snap the DataTable to the grid, when every time I make some changes to the DataTable , there is no need for a ReBind myGrid .
How to solve it without going over every time?
The list does not implement IBindingList , so the grid does not know about your new elements.
Bind your DataGridView to a BindingList<T> .
var list = new BindingList<Person>(persons); myGrid.DataSource = list; But I would even go further and bind your grid to a BindingSource
var list = new List<Person>() { new Person { Name = "Joe", }, new Person { Name = "Misha", }, }; var bindingList = new BindingList<Person>(list); var source = new BindingSource(bindingList, null); grid.DataSource = source; Each time you add a new item to the list, you need to re-snap your grid. Something like:
List<Person> persons = new List<Person>(); persons.Add(new Person() { Name = "Joe", Surname = "Black" }); persons.Add(new Person() { Name = "Misha", Surname = "Kozlov" }); dataGridView1.DataSource = persons; // added a new item persons.Add(new Person() { Name = "John", Surname = "Doe" }); // bind to the updated source dataGridView1.DataSource = persons; After adding a new item to persons add:
myGrid.DataSource = null; myGrid.DataSource = persons; Yes, using the INotifyPropertyChanged interface, you can do this without overwriting.
A pretty simple example is available here,
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx