如何从c#中的另一个线程更新datagridview的数据源
我有一个后台线程与 ui 线程一起运行。现在在backgrounder_doWork方法中,我有一个数据表,我正在向其中添加数据库中的信息。我希望它绑定到 ui 线程中的 datagridview 以显示给用户。因此,当 dataTable 使用来自数据库的新信息进行更新时,datagridview 应自动刷新以添加/减去从后台线程接收到的任何新信息行。我该怎么做?我已经尝试过:
private delegate void dGValueDelegate();
private void dGVValue()
{
BindingSource bSource = new BindingSource();
dtFailures.DataSource = bSource;
bSource.DataSource = dt;
}
其中 dt 是类级别变量。在backgrounder_dowork方法内部,一开始我调用dGVVAlue方法,然后信息被添加到后台线程中的数据表中。但是 datagridview 不会显示...
I have a backgrounder thread running along with a ui thread. Now in the backgrounder_doWork method, i have a datatable that i am adding info to from a database. I want it to bind to a datagridview in the ui thread to display to the user. So when the dataTable is updated with new info as it comes in from the database, the datagridview should automatically refresh to add/subtract any new rows of info recieved from the backgrounding thread. How can i do this? I have tried this:
private delegate void dGValueDelegate();
private void dGVValue()
{
BindingSource bSource = new BindingSource();
dtFailures.DataSource = bSource;
bSource.DataSource = dt;
}
where dt is a class level variable. Inside the backgrounder_dowork method, at the beginning i call the dGVVAlue method and then after that the info gets added to the datatable in the backgrounding thread. The datagridview wont display however...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面的代码应该适合您:
在您的问题中,您提到使用 BindingSource,它没有 Invoke 方法 - 如果您有绑定源,您可以在表单上调用:
您也可以使用 Lamda 表达式在单行中执行此操作:
The code below should work for you:
In your question you mention using BindingSource, which does not have an Invoke method - if you have a binding source you can instead Invoke on the form:
You can also do this in a single line using Lamda expressions:
此外,使用 DataGridView.Invoke(Delegate) 方法将允许您确保在 datagridview 所属的线程中对其进行更改。
Also, using the DataGridView.Invoke(Delegate) method will allow you to ensure that you are making the changes to your datagridview in the thread to which it belongs.