0

At my code, I design a GUI that managed in one task . From the Form1 class I send parameters to method to other class at different task and get parameters from the task.

At form1 class I have myEvt_valueChnaged(string s) method that gets string s as argument - string that contain the text of textbox that send from the event at manager class - invoked from different task.

With the received string I update the textbox at the GUI as wrote here:

private void myEvt_valueChnaged(string s)
{
    textBox1.Text = s;
}

with this code I get the error:

invalidoperationexception was unhandled by user code - Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.

I tried to add line at the method : var y =s; and then textBox1.Text=y; but it didn't solve it.

How can I solve this issue?

Cristik
  • 30,989
  • 25
  • 91
  • 127
odedidush
  • 19
  • 4

1 Answers1

1

A UI element may only be changed by the UI thread. You need to Invoke the action instead:

private void myEvt_valueChnaged(string s)
{
    textBox1.Invoke(new Action(() => textBox1.Text = s));
}
UncleDave
  • 6,872
  • 1
  • 26
  • 44