1
Reply

Endless strings display

Giovanni Garcia

Giovanni Garcia

Aug 9 2011 10:16 PM
1.3k
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]);
}
}

Answers (1)