绑定列表< T>要在winform的DataGridView [英] Binding List<T> to DataGridView in WinForm

查看:89
本文介绍了绑定列表< T>要在winform的DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似下面的类。

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

和我创建了一个列表<人> 然后添加一些项目到这个列表并绑定到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆