Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi I am writing a code in which i got a data from serial port in a textbox. Now I want that data to be in datagrid. The output is as follows:
------------------------------JL206F ID:VDE40050

2015/05/29 11:02:19

JBatch_No.:067

JOperator ID:15

--------------------------------

Mixed Counting

W--------------------------------Deposit Amount: 0.00

--------------------------------

denom count value

UVK(|????DW50D 1 50.00

JUVK(|????DW20D 1 20.00

JUVK(|????DW10ND 1 10.00

J--------------------------------

Total: 3 80.00

--------------------------------

Coin: 0.00

--------------------------------

Balance: 0.00

I want my grid to look like this
Name ID Date Time Batch_No Operator ID Deposit amount denom

Count value total coin balance

and my code is as follows when i am splitting data it is giving me error on spli[1] array out of bound. How Can I do it I am new to c#. 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;
using SerialPortListener.Serial;
using System.IO;

namespace SerialPortListener
{
    public partial class MainForm : Form
    {
        SerialPortManager _spManager;
        public MainForm()
        {
            InitializeComponent();

            UserInitialization();
        }

      
        private void UserInitialization()
        {
            _spManager = new SerialPortManager();
            SerialSettings mySerialSettings = _spManager.CurrentSerialSettings;
            serialSettingsBindingSource.DataSource = mySerialSettings;
            portNameComboBox.DataSource = mySerialSettings.PortNameCollection;
            baudRateComboBox.DataSource = mySerialSettings.BaudRateCollection;
            dataBitsComboBox.DataSource = mySerialSettings.DataBitsCollection;
            parityComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.Parity));
            stopBitsComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.StopBits));

            _spManager.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
        }

        
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _spManager.Dispose();   
        }

        void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
        {
            if (this.InvokeRequired)
            {
                // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
                this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e });
                return;
            }

            int maxTextLength = 100000; // maximum text length in text box
            if (tbData.TextLength > maxTextLength)
                tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength);
            
            DataTable dt = new DataTable();
            DataColumn colName = dt.Columns.Add("Name", typeof(string));
            DataColumn colID = dt.Columns.Add("ID", typeof(string));
            DataColumn colDate = dt.Columns.Add("Date", typeof(string));
            DataColumn colTime = dt.Columns.Add("Time", typeof(string));
            DataColumn colBatch_No = dt.Columns.Add("Batch_No.", typeof(string));
            DataColumn colOperatorID = dt.Columns.Add("Operator ID", typeof(string));
            DataColumn colDepAmt = dt.Columns.Add("Deposit Amount", typeof(string));
            DataColumn coldenom =dt.Columns.Add("Denom", typeof(string));
            DataColumn colCount = dt.Columns.Add("Count", typeof(string));
            DataColumn colValue = dt.Columns.Add("Value", typeof(string));
            DataColumn colTotal = dt.Columns.Add("Total", typeof(string));
            DataColumn colCoin = dt.Columns.Add("Coin", typeof(string));
            DataColumn colBal = dt.Columns.Add("Balance", typeof(string));
            string str = Encoding.ASCII.GetString(e.Data);
            string[] stringSeparators = new string[] { "\n\n\r" };
            string[] lines = str.Split(stringSeparators,StringSplitOptions.None );
            foreach (var line in lines)
            {
                string[] split = line.Split(stringSeparators, StringSplitOptions.None);
                DataRow row = dt.NewRow();
                row.SetField(colName,split[0]);
                row.SetField(colID,split[1]);
                row.SetField(colDate,split[2]);
                row.SetField(colTime,split[3]);
                row.SetField(colBatch_No,split[4]);
                row.SetField(colOperatorID,split[5]);
                row.SetField(colDepAmt,split[6]);
                row.SetField(coldenom,split[7]);
                row.SetField(colCount,split[8]);
                row.SetField(colValue,split[9]);
                row.SetField(colTotal,split[10]);
                row.SetField(colCoin,split[11]);
                row.SetField(colBal,split[12]);

            dt.Rows.Add(row);

            
            tbData.AppendText(str);
             tbData.ScrollToCaret();

        }
        }

        // Handles the "Start Listening"-button click event
        private void btnStart_Click(object sender, EventArgs e)
        {
            _spManager.StartListening();
        }

        // Handles the "Stop Listening"-button click event
        private void btnStop_Click(object sender, EventArgs e)
        {
            _spManager.StopListening();
        }

        private void serialSettingsBindingSource_CurrentChanged(object sender, EventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void tbData_TextChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        
    }
}
Posted
Comments
[no name] 4-Jun-15 7:36am    
Why are you not checking the number of elements in your array after your split? That is what the error is telling you. You are trying to access an element of the array that does not exist.

1 solution

You are trying to separate your string with the same separators twice!
First str is separated to the lines:
C#
string[] stringSeparators = new string[] { "\n\n\r" };
string[] lines = str.Split(stringSeparators,StringSplitOptions.None );

...then you try to separate the items of lines again:

C#
foreach (var line in lines)
 {
   string[] split = line.Split(stringSeparators,StringSplitOptions.None);
...

this is contradiction, because the separator characters are removed in the first split. You should choose different separator for the second separation.
 
Share this answer
 
Comments
[no name] 4-Jun-15 8:41am    
ok i put the other delimiter character as ':' still same error
CzimerA 5-Jun-15 2:13am    
Do you use different delimiters for the two splits?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900