Reputation: 16714
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:
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
.
ComboBox.DropDownStyle
to Simple
and see it not working!Any help with this issue please?
Upvotes: 0
Views: 1344
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