gpt4 book ai didi

winforms - "BindingSource cannot be its own data source"- 尝试从另一个类中的方法重置绑定(bind)源时出错

转载 作者:行者123 更新时间:2023-12-04 13:14:03 24 4
gpt4 key购买 nike

我们正在绑定(bind) DataGridview使用 BindingSource .所以在主线程中我们给出了这样的。

            class1BindingSource = new BindingSource();
class1BindingSource.DataSource = class1List;
this.dataGridView1.DataSource = class1BindingSource;

之后,我在表单中放置了一个后台工作人员,并在单击按钮时触发。

即在按钮中单击
this.backgroundWorker1.RunWorkerAsync()

BackgroundWorker DoWork Event我正在尝试更新 BindingSource并在那里尝试更新 DataGridview .

所以 BindingSource重置是在另一个类的方法中完成的。
DoWork Event
Class2 cl2 = new Class2();
cl2.UpdateBindingSource(class1BindingSource);
UpdateBindingSource Method
public void UpdateBindingSource(BindingSource bs)
{
Class1 c1 = bs.Current as Class1;
for (int i = 0; i < 1000; i++)
{
lock (bs.SyncRoot)
{
c1.MyProperty1 = i;
bs.ResetItem(0);
}
}
}

现在我得到一个异常(exception),如 BindingSource不能是它自己的数据源。不要设置 DataSourceDataMember属性到引用回 BindingSource 的值.

如果我在我的 DoWork Event 中这样做然后我可以使用 BeginInvoke method 重置控制线程本身中的项目.

但实际上我正在尝试模拟我们的应用场景。所以我想以这种格式解决这个问题。

谁可以帮我这个事。

最佳答案

问题是您无法更新 BindingSource在 gui 线程以外的线程中。这是因为 BindingSource将触发一些事件,然后您的数据 GridView 将接收这些事件,然后开始自我更新,这将失败,因为它不会在 gui 线程上完成。
所以就在您调用 RunWorkerAsync() 之前您应该调用 class1BindingSource.SuspendBinding()在您的RunWorkerCompleted 内您应该调用 class1BindingSource.ResumeBinding() .
还要确保在您的 DoWork你不会在绑定(bind)源上调用任何方法(就像你对 bs.ResetItem(0) 所做的那样)。
并删除此锁定语句。它根本没有任何意义(在你的例子中),如果你真的需要它(在你的真实代码中)考虑使用一些 private object _Gate = new Object();在你的类(class)内避免任何来自外部世界的僵局,导致bs.SyncRoot是公开的。

关于winforms - "BindingSource cannot be its own data source"- 尝试从另一个类中的方法重置绑定(bind)源时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14258488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com