event DataReceived i wpisanie danych do textbox

0

Witam.

Jak próbuje w evencie DataReceived wpisać otrzymane dane na textbox to wyświetla mi błąd:

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

Additional information: Nieprawidłowa operacja między wątkami: do formantu 'dane_box' uzyskiwany jest dostęp z wątku innego niż wątek, w którym został utworzony.

Jak zrobić aby wartość tego textboxa zmieniała mi się po odebraniu danych?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace head_sens
{
    public partial class Form1 : Form
    {
        string dane_otrzymane;

        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            dane_otrzymane = serialPort1.ReadExisting();
            dane_box.Text = dane_otrzymane;
        }
    }
}
0

Otrzymujesz dane asynchroniczne -> inny wątek -> aby aktualizować kontrolki użyj Invoke.

1 użytkowników online, w tym zalogowanych: 0, gości: 1