-2

I'm a new student and basically just got into the topic threading.

What I have to do seems rather simple. I have to make a combobox, but I need to fill it using a different thread. And thats where I ran into trouble, cause;

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

So I did some research, and it seems you cant fill UI elements outside the main thread. So I'm sitting here scratching my head thinking what would be the best thing to do.

Help would be appreciated.

Oh btw, its C# and in windows forms.

         public Customer()
    {
        InitializeComponent();
        Thread red = new Thread(Fill);
        red.Start();
    }
    public void Fill()
    {
        Thread.Sleep(5000);
        ComboBox1.Items.Add(1);
        ComboBox1.Items.Add(2);
        ComboBox1.Items.Add(3);
        ComboBox1.Items.Add(4);
        ComboBox1.Items.Add(5);
        ComboBox1.Items.Add(6);
        ComboBox1.Items.Add(7);
    }
meowlady
  • 1
  • 1
  • 1. Provide the actual code that is causing the problem. 2. use the proper tags. This question is about C# and Winforms, not about C – UnholySheep Nov 06 '16 at 15:54
  • It deleted my # somehow, I know C is different. But thanks, I'll do that now – meowlady Nov 06 '16 at 15:56
  • 2
    And by the way, modifying UI elements from different threads is forbidden in most GUI frameworks (for good reasons), whoever told you that that is what you should do was either unclear or wrong. – UnholySheep Nov 06 '16 at 16:06

1 Answers1

-1

You should consider using the Task Parallel Library, creating a Thread explicitly is considered legacy code nowadays. However, to fix your code, you need to invoke the UI updates on the UI Thread.

public void Fill()
{
   Thread.Sleep(5000);

   Action doUIWork = () => 
   {
      ComboBox1.Items.Add(1);
      ComboBox1.Items.Add(2);
      ComboBox1.Items.Add(3);
      ComboBox1.Items.Add(4);
      ComboBox1.Items.Add(5);
      ComboBox1.Items.Add(6);
      ComboBox1.Items.Add(7);
   };

   this.Invoke(doUIWork);
}
Zein Makki
  • 29,485
  • 6
  • 52
  • 63