Cross-thread operation not valid: Control ‘textBox1’ accessed from a thread other than the thread it was created on [duplicate]

I want to send temperature value from a microcontroller using UART to C# interface and Display temperature on Label.Content. Here is my microcontroller code:

while(1) {
   key_scan(); // get value of temp
   if (Usart_Data_Ready())
   {
      while(temperature[i]!=0)
      {
         if(temperature[i]!=' ')
         {
            Usart_Write(temperature[i]);
            Delay_ms(1000);
         }
         i = i + 1;
      }
      i =0;
      Delay_ms(2000);
   }
}

and my C# code is:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
   txt += serialPort1.ReadExisting().ToString();
   textBox1.Text = txt.ToString();
}

but exception arises there “Cross-thread operation not valid: Control ‘textBox1’ accessed from a thread other than the thread it was created on
Please tell me how to get temperature string from my microcontroller and remove this Error!

6 Answers
6

Leave a Comment