C
C#11mo ago
Gibbo

❔ updating a DGV from another form on another thread

hi all, I'm wondering if you can help me with an issue I'm having updating a DGV. I'm getting a thread operation error as below: Cross-Thread operation not valid: Control 'dvgUSBDongles' accessed from a thread other than the thread it was created on Now I understand why I'm getting this and its because the form I'm trying to access it on was generated from a BackgroundWorker(so on a seperate thread) but im not too clued up on this currently and am unsure how to fix it. Everything ive done so far ive managed to do from from alot of googling. but threads/threading is just meh!!!! this is my code:
if (InvokeRequired == true)
{
Invoke(new Action(() => { mainformFunctions.RefreshData(); }));
Invoke(new Action(() => { this.Close(); }));
}
else
{
mainformFunctions.RefreshData();
this.Close();
}
if (InvokeRequired == true)
{
Invoke(new Action(() => { mainformFunctions.RefreshData(); }));
Invoke(new Action(() => { this.Close(); }));
}
else
{
mainformFunctions.RefreshData();
this.Close();
}
6 Replies
Pobiega
Pobiega11mo ago
you need to invoke it on the mainforms thread
Gibbo
Gibbo11mo ago
any examples?
Pobiega
Pobiega11mo ago
mainForm.Invoke(() => ...);
mainForm.Invoke(() => ...);
Gibbo
Gibbo11mo ago
ok thank you, il play about some more ok i think i possibly undertand, where i have my form loading like so
newUSB.ShowDialog();
newUSB.ShowDialog();
i should of
Invoke(new Action(() => { newUSB.ShowDialog(); }));
Invoke(new Action(() => { newUSB.ShowDialog(); }));
this in turn pushes the form back to the primary thread please correct me if im wrong thanks @pobiega
Pobiega
Pobiega11mo ago
uh, maybe? Im not sure how it works with opening new windows, but probably the thing with Invoke is that it schedules the action you pass to run on the UI thread owned by the thing you call Invoke on
Accord
Accord11mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.