Friday, April 24, 2009

Cross-thread operation not valid: Control 'Ctrl' accessed from a thread other than the thread it was created on

I though I would have to redesign part of the application, after all, this seems like a critical error. But if you come across this error, check out this link:

http://www.vcskicks.com/cross-thread.php

Delegates can fix it. The code below will help you (part of this code is from the website above).

 
private delegate void AddListBoxItemDelegate(object item);
... then copy this code inside your method...
if (this.InvokeRequired)
{
AddListBoxItemDelegateaddItemDel = new AddListBoxItemDelegate
(AddListBoxItem); //delegate
object[] parameters = { text }; //parameters
this.Invoke(addItemDel, parameters); //call
}

else

{
//code you want to execute
}