Binding List<T> to DataGridView in WinForm

namco picture namco · May 22, 2013 · Viewed 243.6k times · Source

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 items. 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;

There is no problem. myGrid displays two rows, but when I add new items to my persons list, myGrid does not show new updated list. It only shows the two rows which I added before.

So what is the problem?

Rebinding every time works well. But when I bind a DataTable to the grid when every time when I make some changes to DataTable there is not any need to ReBind myGrid.

How to solve it without rebinding every time?

Answer

J&#252;rgen Steinblock picture Jürgen Steinblock · May 22, 2013

List does not implement IBindingList so the grid does not know about your new items.

Bind your DataGridView to a BindingList<T> instead.

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;