0

I have a form with a ComboBox named cableGaugeSelect. At times I need to read the currently selected index in response to a serial message. The code doesn't have a problem reading text boxes or check boxes, but when it gets to reading the selected index

cableGaugue[0] = (byte) cableGaugeSelect.SelectedIndex;

I get an unhandled exception:

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

It seems I have to use a delegate to get the data from between threads, but all of the examples I found of how to use delegates are of how to put text into a textbox. I am having a lot of trouble figuring out how to create a delegate that will retrieve this information. Any help would be appriciated

chouaib
  • 2,763
  • 5
  • 20
  • 35
  • Is there a reason you are casting an `int` to a `byte`? – mittmemo Feb 23 '15 at 23:56
  • 2
    Cross-thread operation googles very well. You can't access controls in background threads. You need to document this better. The simple way is to pass the information you need as parameters at the start of the thread. – LarsTech Feb 24 '15 at 00:00
  • 1
    _"but all of the examples I found of how to use delegates are of how to put text into a **textbox**"_ - `TextBox`; `ComboBox`; `Listbox` - it does not matter, the solution is the same. No need for another question. Did you attempt to even try the solution you found in the other post? Wishing you well –  Feb 24 '15 at 00:06
  • We are designing a piece of industrial equipment (I don't want to divulge too much detail) for the purpose of giving to an outside company this is developing a phone app that talks to our industrial equipment. The form contains a bunch of data fields, some represented by text boxes, some by check boxes, and some by combo boxes, that represent various setting on the equipment. A serial message comes in that asks for the status of the "machine" and the code reads the appropriate data from the form, then formats it into a response. – Keith Kolb Feb 24 '15 at 00:22
  • I'm not a very good programmer so the code is something that I've hacked together through google searches on how to do this or that, but I've hit a point where I can't quite figure it out. I've found good examples of how to use delegates to put data INTO the form, but not so much how to get it OUT. – Keith Kolb Feb 24 '15 at 00:23
  • possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) –  Feb 24 '15 at 03:23

1 Answers1

3

If you want to touch controls, you need to do it on the UI thread. You can do this by utilizing Control.Invoke().

cableGuageSelect.Invoke(new Action(() =>
    {
        cableGuage[0] = (byte)cableGuageSelect.SelectedIndex;
    }));
itsme86
  • 19,266
  • 4
  • 41
  • 57