绑定列表&LT; T&GT;要在winform的DataGridView [英] Binding List<T> to DataGridView in WinForm
问题描述
我有类似下面的类。
class Person{
public string Name {get; set;}
public string Surname {get; set;}
}
和我创建了一个列表&LT;人&GT;
然后添加一些项目到这个列表并绑定到 DataGridView的
。
And i create a List<Person>
then add some items to this list and bind it to 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
显示两行。结果
但是,当我从方案添加新项目人
列表 myGrid
不结果
显示新的更新列表。它显示只有两排,我前加入。结果
所以,这是什么问题?结果
重新绑定每一次效果很好。结果
但是,当我绑定数据表
时,每次当我做一些修改 DataTable的时间
有对电网没有任何需要重新绑定 myGrid
。结果
如何解决它没有重新绑定每次?
There is not any problem. myGrid
displays two rows.
But when i from program add new items to persons
list myGrid
does not
show new updated list. It shows only 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?
推荐答案
列表不落实 IBindingList的
所以网格不知道你的新项目。
List does not implement IBindingList
so the grid does not know about your new items.
绑定你的DataGridView到的BindingList&LT; T&GT;
而不是
Bind your DataGridView to a BindingList<T>
instead.
var list = new BindingList<Person>(persons);
myGrid.DataSource = list;
不过,我甚至会更进一步,网格绑定到的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;
这篇关于绑定列表&LT; T&GT;要在winform的DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!