在 WinForm 中绑定 List < T > 到 DataGridView

我还有课

class Person{
public string Name {get; set;}
public string Surname {get; set;}
}

和一个 List<Person>,我添加了一些项目。该列表是绑定到我的 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;

没问题。myGrid显示两行,但是当我向 persons列表中添加新项时,myGrid不显示新更新的列表。它只显示我之前添加的两行。

那么问题出在哪里呢?

每次都能重新绑定。但是当我把一个 DataTable绑定到网格上的时候,每次当我对 DataTable做一些修改的时候,就不需要重新绑定 myGrid了。

如何解决这个问题而不用每次都重新绑定?

287168 次浏览

Every time you add a new element to the List you need to re-bind 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 new item to persons add:

myGrid.DataSource = null;
myGrid.DataSource = persons;

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;

Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.

Pretty Simple example is available here,

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

This isn't exactly the issue I had, but if anyone is looking to convert a BindingList of any type to List of the same type, then this is how it is done:

var list = bindingList.ToDynamicList();

Also, if you're assigning BindingLists of dynamic types to a DataGridView.DataSource, then make sure you declare it first as IBindingList so the above works.