绑定列表< T>到WinForm中的DataGridView [英] Binding List<T> to DataGridView in WinForm

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

问题描述

我有一个类

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

列表< Person> / code>我添加了一些项目。该列表绑定到我的 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 不显示新的更新列表。它只显示了我之前添加的两行。

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 绑定到网格中,则没有任何需要到ReBind 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?

推荐答案

不实现 IBindingList ,所以网格不了解您的新项目。

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

将您的DataGridView绑定到 BindingList< T>

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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