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

问题描述

我有一堂课

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

和一个 List 我添加了一些项目.该列表绑定到我的 DataGridView.

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;

没有问题.myGrid 显示两行,但是当我将新项目添加到我的 persons 列表时,myGrid 不显示新的更新列表.它只显示我之前添加的两行.

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.

那么问题出在哪里?

每次重新绑定都很有效.但是当我将 DataTable 绑定到网格时,每当我对 DataTable 进行一些更改时,就不需要重新绑定 myGrid.

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?

推荐答案

List 没有实现 IBindingList 所以网格不知道你的新项目.

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

将您的 DataGridView 绑定到 BindingList.

Bind your DataGridView to a BindingList<T> instead.

var list = new BindingList<Person>(persons);
myGrid.DataSource = list;

但我什至会更进一步,将您的网格绑定到 BindingSource

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;

这篇关于绑定列表&lt;T&gt;到 WinForm 中的 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:13