0

i am developing a code in which a have to read the data form list box and upload an external file, press a button named Start and with this listbox i am getting an error as shown below.

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

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

my code is as follows

private void Start_Click(object sender, EventArgs e)
{
 Thread ss = new Thread(Automode);  
 ss.Start(); 
} 

 private void Automode()
    {
        ....
       for (int i = 0; i < listBox1.Items.Count; i++)
        {
            listBox1.SetSelected(i, true);

            string pattern = "[gxyzbcmij][-+]?[0-9]*\\.?[0-9]*";
            string text = listBox1.Text;
            Regex gcode = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection code = gcode.Matches(text);
        }
        .....   
     }

here at listbox.SetSelected command it is giving an exception as shown above. please suggest the alternate ways to write it.

Christoph K
  • 344
  • 6
  • 16
  • As always, separate the UI code from the business code... Redesign it so that the thread code doesn't access the ListBox or any other control. – H H Jan 06 '16 at 12:37

2 Answers2

1
delegate void SetSelectedCall(int index, bool option);

private void SetSelectedElement(int index, bool option)
{
  if (this.listBox1.InvokeRequired)
  { 
    SetSelectedCall d = new SetSelectedCall(SetSelectedElement);
    this.Invoke(d, new object[] { int index, bool option});
  }
  else
  {
    this.listBox1.SetSelected(index,option);
  }
}

Taken from Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on and tailored for this question.

Community
  • 1
  • 1
  • This does solve the immediate problem but it does not address the deeper design issues. – H H Jan 06 '16 at 13:38
0

You can't access the listBox1 from a background thread.

If possible, run the code from the function Automode() directly in the Start_Click method. If you must have the code ran in a background thread, I would perhaps suggest something more like a Task, that way you can still perform the action based on passing arguments and awaiting a response. Then you can still listBox1 items as selected.

PaulieTree
  • 613
  • 6
  • 9