I have an endless amount of data coming through serial port. That same data is then parsed into strings. I want to display those endless strings into a textbox. I believe my code works for the most part. I just keep getting the same error:Index was outside the bounds of the array.
Here is my code:
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 Simple_Serial1
{
public partial class Form1 : Form
{
string RxString;
string[] stringSeparators = new string[] {","};
string[] result;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!serialPort1.IsOpen) return;
char[] buff = new char[1];
buff[0] = e.KeyChar;
serialPort1.Write(buff, 0, 1);
e.Handled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
result = RxString.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.AppendText(result[0]);
}
}
Loading
Amit ChoudharyPosted Aug 10, 2011, 2:49 AM
I think your RxString doesnot have any data in it. watch the data in RsString before splitting the incoming data string.
then check if Result array is having elements. anyways it should not throw any error cause after using split the first index of result array gets value of Empty string. but since you have used the option for RemoveEmptyEntries dats y in case of no data is coming the use of result[0] in display text is throwing error.
Hope this make sense to you.
Thanks.