Blackbriar
Blackbriar

Reputation: 507

Why is combobox throwing exception even though invoke is used

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

Answers (1)

Sir Rufo
Sir Rufo

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

Related Questions