I'm not sure exactly what you expect that code to do:
private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
bytenum = serialport.BytesToRead;
serialport.ReceivedBytesThreshold = 50;
textBox2.BeginInvoke(new MyDelegate(rcvtext));
}
public delegate void MyDelegate();
public void rcvtext()
{
byte[] bytearray = new byte[bytenum];
serialport.Read(bytearray, 0, bytenum);
for (int i = 0; i < bytenum; i++)
{
textBox2.Text += (Convert.ToByte(bytearray[i]).ToString();
}
}
But for starters that's a very poor way to do it: you risk losing data and generally getting messed up by trying to pass the count via a class level variable.
Either pass it via a method parameter, or (better) fetch it from the serial port directly as part of the
tcvtext
method.
What you are doing with the data once you have read it deosn;lt make a lot of sense either:
textBox2.Text += (Convert.ToByte(bytearray[i]).ToString();
So...you take a byte value, convert it to a string, then try to convert the string back to a byte in order to add it to a string?
What part of that made any sense?
If you want to add the "Raw" data to the textbox then either use your loop "as is" but change that line to:
textBox2.Text += (char) bytearray[i];
(or better, use a StringBuilder as an intermediary), or replace the whole loop and convert the whole array:
textBox2.Text += System.Text.Encoding.ASCII.GetString(bytearray);
If you are trying to output the values as readable hex values, that's even easier:
textBox2.Text += BitConverter.ToString(bytearray);