Reputation: 507
I am trying to set the selected item of a combobox from another thread but the software is throwing an Exception with the message "Cross-thread operation not valid. Control xxx accessed from a thread other than the thread it was created"
I already tried to use a MethodInvoker if InvokeRequired is true on the ComboBox, but I am still getting the Exception.
public class ComboBoxAdapter
{
System.Windows.Forms.ComboBox comboBox;
//...
public void setSelectedItem( object item ) {
if ( comboBox.InvokeRequired )
comboBox.Invoke( new MethodInvoker( () => setSelectedItem( item ) ) );
comboBox.SelectedItem = item;
}
}
I do not expected an exception if I am accessing the ComboBox like in my code.
Upvotes: 1
Views: 384
Reputation: 19106
You miss an else
public void setSelectedItem( object item ) {
if ( comboBox.InvokeRequired )
comboBox.Invoke( new MethodInvoker( () => setSelectedItem( item ) ) );
else
comboBox.SelectedItem = item;
}
otherwise you direct update the control even when Invoke is Required.
Upvotes: 1