Click here to Skip to main content
15,910,358 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Cross-thread operation not valid: Control listbox1 accessed from a thread other than the thread it was created on

I have delegate for ADD items in ListBox. Before add new item I check is it already in the list If yes then Remove from the List and add new one.


As I tried to remove old item It gives error.

"Cross-thread operation not valid: Control listbox1 accessed from a thread other than the thread it was created on"


Can't I do both operation together in single call??

Please help me!!! :(


Thank you
Seema
Posted

You should only access UI elements from the thread that created them

How to: Make Thread-Safe Calls to Windows Forms Controls [^]

Use the 'InvokeRequired' property of your listbox to see if you need to marshal back to the UI thread

e.g.

C#
private void LoadItems()
{
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    if (this.listbox1.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {
        // Load your items here
    }
}


Alternatively, if you're using .Net 4.0, you might want to look at the Task Parallel Library[^] which allows you to use continuations and pass a Synchronization Context that automatically marshalls back to the UI

http://blogs.msdn.com/b/csharpfaq/archive/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context.aspx[^]

Edit: Just noticed the .Net 3.5 tag! I'll leave the TPL reference in my answer though, might help someone else
 
Share this answer
 
v2
Comments
Sandeep Mewara 16-Feb-11 5:57am    
Good answer! 5!
johannesnestler 16-Feb-11 10:00am    
Excelent Answer Dylan! So what you should do now:
Blindly copy it as answer to any question here on CP, chances are good that you hit an appropriate question. *gg*
Sergey Alexandrovich Kryukov 16-Feb-11 12:50pm    
Very good, my 5.
--SA
Leave alone Google, did you even try to find answer on CP before posting the question.
I did the google search and the first result was for this [^]on Code Project.

It explains it nicely.
 
Share this answer
 
Comments
Seema Gosain 16-Feb-11 10:09am    
Yes, I also tried and found but my issue is to remove the items.Forthis I Listbox1.InvokeRequired{}else{}
But I want to remove item before adding new item :(
Sergey Alexandrovich Kryukov 16-Feb-11 12:50pm    
This is VB.NET (what can VB be good :-), C# requested. You're right about Google and CP, of course.
--SA

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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