0

I have to check if a listbox's SelectedIndex is at the last index from a BackgroundWorker, but since I'm checking the listbox (which is on the GUI thread) from the BackgroundWorker I get this error:

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

This is my code:

if (listBox1.SelectedIndex == listBox1.Items.Count)
{
//code here
}

How could I make this if statement work without being on the GUI thread?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Thomas
  • 11
  • 2

1 Answers1

-1

This basically happens when you access the forms property from another thread, that's why this exception is thrown. Your UI operations must be performed on the owning thread.

You can do this:

 int intIndex = 0;
 int intCount = 0;
        if (listBox1.InvokeRequired)
        {
            listBox1.Invoke(new MethodInvoker(delegate { intIndex = listBox1.SelectedIndex ; }));
        }

        if (listBox1.InvokeRequired)
        {
            listBox1.Invoke(new MethodInvoker(delegate { intCount = listBox1.Items.Count; }));
        }

Then your condition here:

        if (intIndex == intCount)
        {
            // TODO: Business Logic
        }

Or you can do this quick fix but not advisable on production but you can do on development. You can add this on your constructor Form:

CheckForIllegalCrossThreadCalls = false;
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
  • No. One should *never* set `CheckForIllegalCrossThreadCalls` to `false`. All that does is delay finding the problems that using a control from the wrong thread will inevitably cause. – Peter Duniho Sep 20 '17 at 03:01
  • Thanks, this is exactly what I was looking for. Gonna test it when I get home! – Thomas Sep 20 '17 at 14:29
  • Okay, let me know if it works, you can accept it as answer if this answers your question, thanks! @Thomas – Willy David Jr Sep 21 '17 at 00:17
  • It worked perfectly, not sure how to mark it as an answer on mobile though. – Thomas Sep 21 '17 at 00:19