-1

Upon tick of my timer i am reading 9 byte of data from my sensor, i am converting the read string to HEX form the data is 01-03-04-0A-D5-15-A9-26-FD right now the only data concerned with me is 4th & 5th element i am using split command to split my string but still i am unable to access exception pops out Indexoutofrangeexception, when itry to access 4th element by index 3,

  private void timer1_Tick(object sender, EventArgs e)
        {
           // timer1.Enabled = false;
            serialPort1.Write(query, 0, query.Length);
            incoming = serialPort1.ReadExisting();

         ba = Encoding.Default.GetBytes(incoming);
        var hexString = BitConverter.ToString(ba);

        textBox1.Text = incoming;
        textBox2.Text = hexString;

       string[] splittedResult = hexString.Split('-');
        textBox3.Text = splittedResult[3];
        //label1.Text = splittedResult[1];



       // textBox3.Text = Convert.ToString(hexString.Length);


        timer1.Enabled = true;
    }
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Please only use the `visual-studio` tag for questions pertaining to Visual Studio (not code you write with it). – ProgrammingLlama Jan 24 '19 at 06:42
  • 2
    Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – ProgrammingLlama Jan 24 '19 at 06:42
  • 3
    If you debugged this you would realise, the data you "think" you are getting is not the data you "are" getting. meaning you are probably reading partial chunks. Which would change your question from *"unable to access element array"* to *"How to ensure i read all the data i need from a serial port"* – TheGeneral Jan 24 '19 at 06:43
  • 1
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) and [First look at the Visual Studio Debugger](https://learn.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2017) are probably useful links to check. – ProgrammingLlama Jan 24 '19 at 06:44

1 Answers1

2

Maybe hexString is null or it's value is shorter than you think. Try this:

...
string[] splittedResult = hexString.Split('-');
if (splittedResult.Length >=4 ) // check lenght
    textBox3.Text = splittedResult[3];
...
emert117
  • 1,268
  • 2
  • 20
  • 38