简体   繁体   English

将数据网格绑定到Winforms应用程序中的对象列表时添加记录

[英]Adding records when binding a datagrid to a list of objects in a winforms app

I have the following classes: 我有以下课程:

public class MyItems : List<MyItem>
{
...
}

public class MyItem
{
...
}

I've instantiated MyItems and assigned it to the DataSource property of a WinForms datagrid. 我已实例化MyItems并将其分配给WinForms数据网格的DataSource属性。

Everything displays properly, but when I try to add rows, nothing happens. 一切显示正常,但是当我尝试添加行时,什么也没发生。 What I do is case the grids DataSource back to MyItems, add an instance of MyItems to it, and then set the DataSource back to the list. 我要做的是将DataSource网格返回MyItems,向其添加MyItems实例,然后将DataSource设置回列表。 I can step through the code and see that the count of items in the datasource is growing, but the grid isn't displaying them. 我可以遍历代码,看到数据源中的项目数正在增长,但是网格未显示它们。 Any ideas? 有任何想法吗?

//Form Load
MyItems lstItems = new MyItems();
lstItems.Add(new MyItem("1"));
lstItems.Add(new MyItem("2"));

//Grid displays two rows;
grd.DataSource = lstItems;

//Add button click event
MyItems lstItmes = (MyItems)grd.DataSource;
lstItems.Add(new MyItem("3"));

//Grid does not display new row
grd.DataSource = lstItems;

In order for changes to the data source to show up, it must implement the System.ComponentModel.IBindingList interface. 为了显示对数据源的更改,它必须实现System.ComponentModel.IBindingList接口。 This is the interface that provides the ListChanged event, which is what the grid hooks into in order to discover changes to the list (adding and removing items) or to rows (changing property values). 这是提供ListChanged事件的接口,网格为了将列表(添加和删除项)或行(更改属性值)的更改发现而钩入了该事件。

Additionally, the ITypedList interface is what allows the designer to discover properties and how the grid can perform data binding with better performance than reflection-based binding. 此外, ITypedList接口使设计人员能够发现属性以及网格如何执行数据绑定,从而比基于反射的绑定具有更好的性能。

If you're just looking for basic notifications and your base class already inherits from something like List<T> , try changing the parent to System.ComponentModel.BindingList<T> . 如果您只是在寻找基本通知,并且您的基类已经继承自List<T> ,请尝试将父类更改为System.ComponentModel.BindingList<T> This has a simple implementation of the IBindingList interface already. 这已经具有IBindingList接口的简单实现。 You'll have to do more work if you want more advanced things like sorting or support property change notification, but it provides the implementation for basic adding and removing. 如果需要更高级的功能(例如排序或支持属性更改通知),则必须做更多的工作,但是它提供了基本添加和删除的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM