LomidzeAlex
LomidzeAlex

Reputation: 41

C# - Serial Port Listening - How to print data into textBox

I want to create Serial port listener with GUI. I'm trying to print received data into textBox. When i click button program has to start listening, everything works but not printing into textBox. Here is EventHandler code:

void serialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            textBox1.AppendText(indata + "\r\n");
        }

And the button code which starts listening:

mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();

Need some help :)

Upvotes: 1

Views: 1903

Answers (1)

AT-2017
AT-2017

Reputation: 3149

You can use RichTextBox as follows:

1st option:

RichTextBox1.Text += sp.ReadExisting() + "\n";

2nd option - The second option uses delegate, you can say, a signature of method:

public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;

private void Form1_Load(object sender, EventArgs e)
{
    this.myDelegate = new AddDataDelegate(AddDataMethod);
}

public void AddDataMethod(String myString)
{
    TextBox1.AppendText(myString);
}

private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
   SerialPort sp = (SerialPort)sender;
   string s= sp.ReadExisting();

   TextBox1.Invoke(this.myDelegate, new Object[] {s});       
}

Upvotes: 1

Related Questions