简体   繁体   English

Winforms:如何将列表绑定到多个DataGridView

[英]Winforms: How to Bind a List to multiple DataGridView

I want to be able to bind a List to multiple DataGridViews such that manipulation through one of the gridviews would be propogated to all other gridviews. 我希望能够将一个List绑定到多个DataGridViews,以便将通过其中一个gridviews进行的操纵传播到所有其他gridviews。

List<Domain> data;

1st approach: 第一种方法:

BindingList<Domain> list = new ..;
data.ForEach( d => { list .Add(d); } );    

grid1.DataSource = list;
grid2.DataSource = list;

This didn't work. 这没用。 The grids share properties other than the data. 网格共享数据以外的属性。

2nd approach: 第二种方法:

BindingList<Domain> list1 = new ..;
BindingList<Domain> list2 = new ..;

data.ForEach( d => { list1.Add(d); list2.Add(d); } );    

grid1.DataSource = list1;
grid2.DataSource = list2;

This approach works for updates. 此方法适用于更新。 However, adds and deletes weren't propograted. 但是,未建议添加和删除。

3rd approach: 第三种方法:

BindingList<Domain> list = new ..;
data.ForEach( d => { list .Add(d); } );    

BindingSource ds1 = new BindingSource();
BindingSource ds2 = new BindingSource();
ds1.DataSource = list;
ds2.DataSource = list;

grid1.DataSource = ds1;
grid2.DataSource = ds2;

This propogates adds and deletes, however, when a new row is added to 1 view, but not yet commited, an empty row is displayed in all other grids. 它传播添加和删除,但是,当将新行添加到1个视图但尚未提交时,在所有其他网格中将显示一个空行。 Seems like a new record is inserted into the List before the editing completes. 好像是在完成编辑之前将新记录插入到列表中。

How can I properly bind multiple datagridviews to one List? 如何将多个datagridviews正确绑定到一个列表? (This is extremely easy in Flex.) I'd appreciate any reference to the relevant section in MDSN. (在Flex中,这非常容易。)我非常感谢对MDSN中相关部分的引用。

I made a little test app, just to make sure that sharing a binding source was possible the way I remembered. 我制作了一个小测试应用程序,目的是确保以记住的方式共享绑定源。 You can find it here (for at least 30 days). 您可以在这里找到它(至少30天)。

What I found that propbably caused your problem is that all your grids probably have adding/deleting rows enabled. 我发现可能引起您问题的原因是,所有网格都可能启用了添加/删除行。 A new row in grid1 is displayed as a new row in grid2, but grid2 (quite unnecessarily) displays a template row below that. grid1中的新行显示为grid2中的新行,但是grid2(不必要地)在其下面显示模板行。

I made a little main window with a read-only grid on a binding source and an edit dialog with an editable grid on the same binding source. 我做了一个小的主窗口,在绑定源上有一个只读网格,在同一绑定源上有一个可编辑网格的编辑对话框。 The binding source is the only wiring between the two, no event handling to signal updates, no reassigning of datasources. 绑定源是两者之间的唯一连线,没有事件处理来通知信号更新,也没有重新分配数据源。 Everything is synced perfectly, even the current row (because of the CurrencyManager ). 一切都完美同步,即使当前行也是如此(由于CurrencyManager )。 A new row in the dialog only shows as one empty row in the 'main' window. 对话框中的新行仅在“主”窗口中显示为一个空行。

Hope this helps, and is not over-simplified. 希望这会有所帮助,并且不要过于简化。

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

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