I’m writing a program that handles DBs and writes any changes into ListView for user to proccess them. After that It is suposed to write all changes back into DB but I can’t figure out how to reach ListView.ListViewItemCollection from BGW. I’ve tried to use Control.Invoke but I’m affraid I’m not yet skilled enough to make it work.
The error I’m getting says I can’t access that control from thread that it was not created on
private delegate void BGOUdate(ListView.ListViewItemCollection lvic);
BGOU = new BGOUdate(ApplyChanges);
bgw1.RunWorkerAsync(lvProducts.Items);
private void bgwSearcher_DoWork(object sender, DoWorkEventArgs e)
{
BGOU(e.Argument as ListView.ListViewItemCollection);
}
private void ApplyChanges(ListView.ListViewItemCollection lvic)
{
...
foreach (ListViewItem item in lvic)
{
...
}
...
}
Control.Invokeis the right way to walk. But you need to pass the control to the background worker, not just itsItemCollection:This way, all changes to the ListViewItems will be made in the thread that created the controls.
Actionis a predefined void delegate that takes no arguments. The keyworddelegatemarks the following block as an anonymous function and returns a delegate to this, which is then cast to anActionthat can be invoked on the control. The call toInvokecauses the passed delegate to be executed on the thread that is associated with the control’s window handle, which is almost everytime the creator thread.Maybe, you should consider DataBinding as an option to keep GUI elements in sync with your data.