Diego
Diego

Reputation: 16714

"Cross-thread operation not valid" if ComboBox.DropDownStyle == Simple

I have a Forms that is shown in a method called through Invoke because that method is called from a different thread. In the form I need to open I have a UserControl with a ComboBox in it. If the ComboBox.DropDownStyle is Simple the form.Show explodes throwing

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

If I set ComoBox.DropDownStyle in the default value (DropDown) I have no problem.

I now this is kind of hard to understand (even believe) so here there is a simplified example to reproduce it:

  1. Create a new winforms project.
  2. Create two forms and a user control.
  3. In the user control create a ComboBox.
  4. In the Form2 put an instance of the user control.
  5. In the Form1 code put this:


private Form form;
private delegate void ShowDelegate();
private ShowDelegate showDelegate;

private void Form1_Load(object sender, EventArgs e)
{
    showDelegate = Show;
    new Thread(Run).Start();
}

private void Run()
{
    form = new Form2();
    Invoke(showDelegate);
}

private void Show()
{
    form.Show();
}

Remember to set the event to Form1_Load.

  1. Run it and see it working.
  2. Change the ComboBox.DropDownStyle to Simple and see it not working!

Any help with this issue please?

Upvotes: 0

Views: 1344

Answers (1)

aybe
aybe

Reputation: 16672

By simply moving

form = new Form2();

To your Show() method, it will work then.

The Form gets initialized on the thread you start, it works then. But you might want to check the behavior in the long term ...

Upvotes: 2

Related Questions