0

All, a new bee here, and I am seeking some help. I am at a lost. Below you will find a portion of my code where I take the < and > out of my string received from a serial port. This all works great until I send a serial message back to the other device(Just a button programed to send a message). Then program stops and tells me "System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.".

It stops at "string CleanString1 = withoutStartOfString1.Remove(endOfString1);"

All your help will be appreciated.

private void DataReceivedHandler1(object sender1, SerialDataReceivedEventArgs e )
    {
        SerialPort sp1 = (SerialPort)sender1;
        string indata1 = sp1.ReadLine();
        Console.WriteLine("Data Received1:"+ indata1);

            int startOfString1 = indata1.IndexOf('<');
            string withoutStartOfString1 = indata1.Remove(0, startOfString1 + 1);
            int endOfString1 = withoutStartOfString1.LastIndexOf('>');
            string CleanString1 = withoutStartOfString1.Remove(endOfString1);
            txtReceive1.BeginInvoke((new myDelegate1(Serial_Text_Out1)), CleanString1);



        txtReceive1.BeginInvoke ((new myDelegate1(Serial_Text_Out1)), CleanString1);

        /*
        *          ROBOT 1            Section to convert "CleanSting so it can be used else where
        */
        void Serial_Text_Out1(string Clean1String1)
        {
            txtReceive1.Text= Clean1String1;
            string[] words1 = CleanString1.Split(',');
            txtIdentifier1.Text = words1[0];
            txtValue1_1.Text = words1[1];
            txtValue1_2.Text = words1[2];
            txtValue1_3.Text = words1[3];
            txtValue1_4.Text = words1[4];                                              
        }

    }
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • `StartIndex cannot be less than zero` im guessing you are smart enough to know what this might mean? so good sir, you are on your way. the next thing you want to do is debug your code. Start with this https://learn.microsoft.com/en-us/visualstudio/debugger/navigating-through-code-with-the-debugger?view=vs-2017 and maybe this https://www.dotnetperls.com/debugging – TheGeneral Jan 09 '19 at 03:32
  • `startOfString1` or `endOfString1` has been set to -1. – mjwills Jan 09 '19 at 03:46

1 Answers1

0

Problem starts here:

int endOfString1 = withoutStartOfString1.LastIndexOf('>');

endOfString1 < 0. It means, that withoutStartOfString1 does not contain > char.

Maybe it's better to use string.Split method like this:

string[] data = indata1.Split(new[]{'<', '>'}, StringSplitOptions.RemoveEmptyEntries);

And get value from array.

Backs
  • 24,430
  • 5
  • 58
  • 85