Click here to Skip to main content
15,441,568 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I am trying to access a combobox created by drop down from the toolbox and then created a new Thread and trying add items in the combobox through the newly created thread and tje error arise like Cross-thread operation not valid: Control 'comboBox1' accessed from a thread other than the thread it was created on.

all the valuable solution will be appreciated
[no name] 12-Jul-13 7:00am    
Well the obvious solution is not to try and access controls from the non-UI thread. If you insist that you just have to do it, then use a Dispatcher for WPF or Control.Invoke for Winforms.
rajeeshsays 24-Jul-13 5:30am    
Solution 1 is good. I could run my program properly by add this line of code
rajeeshsays 24-Jul-13 5:31am    
Thank Mr.Kim Togo

1 solution

You can only change UI Control elements from the same thread that created them. Usually Main Thread (UI Thread).
If it is WinForm, you have to switch from worker thread to Main Thread via Control.Invoke[^] commands.

You can do something like this:
Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread"));
Share this answer
rajeeshsays 12-Jul-13 7:45am     CRLF
private void AddValue() { this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread"))); //comboBox1.Items.Add("hai"); } private void Form1_Load(object sender, EventArgs e) { MessageBox.Show("Current Thread" + Thread.CurrentThread.Priority); } private void button1_Click(object sender, EventArgs e) { Second = new Thread(new ThreadStart(this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread")));); Second.Start(); }
rajeeshsays 12-Jul-13 7:46am     CRLF
this is my code can you please tell what is wrong with it?
Kim Togo 12-Jul-13 7:59am     CRLF
Yes I can. Change: Second = new Thread(new ThreadStart(this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread")));); To: Second = new Thread(() => this.Invoke(new Action(() => comboBox1.Items.Add("Hello from Thread"))));
Sushil Mate 12-Jul-13 8:18am     CRLF
much better than +5, mine deleted :)
Kim Togo 12-Jul-13 8:23am     CRLF
Thanks Sushil :-) But you do not need to delete your solution if it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900