1

I'm working with the following VB code:

Option Strict On
Option Infer On

Public Class mainForm

    Private readBuffer As String = String.Empty
    Private Bytenumber As Integer = 1
    Private ByteToRead As Integer = 1
    Private byteEnd(2) As Char
    Private comOpen As Boolean


    Private Sub Form1_FormClosed(ByVal sender As System.Object, _
                                 ByVal e As System.Windows.Forms.FormClosedEventArgs) _
                                 Handles MyBase.FormClosed
        If comOpen Then SerialPort1.Close()
    End Sub


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        sensorButton.Checked = True
        ' read avaiable COM Ports:
        Dim Portnames As String() = System.IO.Ports.SerialPort.GetPortNames
        If Portnames Is Nothing Then
            MsgBox("There are no Com Ports detected!")
            Me.Close()
        End If
        cboComPort.Items.AddRange(Portnames)
        cboComPort.Text = Portnames(0)
        cboBaudRate.Text = "115200"

    End Sub


    Private Sub btnComOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComOpen.Click

        ' device params
        With SerialPort1

            .ParityReplace = &H3B                    ' replace ";" when parity error occurs
            .PortName = cboComPort.Text
            .BaudRate = CInt(cboBaudRate.Text)
            .Parity = IO.Ports.Parity.None
            .DataBits = 8
            .StopBits = IO.Ports.StopBits.One
            .Handshake = IO.Ports.Handshake.None
            .RtsEnable = False
            .ReceivedBytesThreshold = 1             'threshold: one byte in buffer > event is fired
            .NewLine = vbCr         ' CR must be the last char in frame. This terminates the SerialPort.readLine
            .ReadTimeout = 10000

        End With

        ' check whether device is avaiable:
        Try
            SerialPort1.Open()
            comOpen = SerialPort1.IsOpen
        Catch ex As Exception
            comOpen = False
            MsgBox("Error Open: " & ex.Message)
            picOpen.BackColor = Color.Red
        End Try

        If comOpen Then
            picOpen.BackColor = Color.Green
            cboComPort.Enabled = False
            cboBaudRate.Enabled = False
        End If

    End Sub

    ''' <summary>
    ''' close ComPort
    ''' </summary>
    Private Sub Button_Close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComClose.Click
        If comOpen Then
            ' clear input buffer
            SerialPort1.DiscardInBuffer()
            SerialPort1.Close()
        End If
        comOpen = False
        picOpen.BackColor = Color.Red
        picDataReceived.BackColor = Color.Gray
        cboComPort.Enabled = True
        cboBaudRate.Enabled = True
    End Sub

    ''' <summary>
    ''' clear TextBoxes
    ''' </summary>
    Private Sub Button_clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        tbRx.Text = String.Empty

        txTimer.Stop()
    End Sub

    ''' <summary>
    ''' write content of Textbox to Port
    ''' </summary>
    Private Sub button_send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
        ...

    End Sub

    ''' <summary>
    ''' close app
    ''' </summary>
    Private Sub Button_ende_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        If comOpen Then
            ' clear input buffer
            SerialPort1.DiscardInBuffer()
            SerialPort1.Close()
        End If
        comOpen = False
        Me.Close()
    End Sub

    ''' <summary>
    ''' send control panel key to com port
    ''' </summary>
    ''' <param name="sender">return key name</param>
    Private Sub Tasten_Click(ByVal sender As System.Object,
                             ByVal e As System.EventArgs)


        Dim key As String = CType(sender, Button).Text
        If comOpen Then SerialPort1.Write(key)

    End Sub

    ''' <summary>
    ''' Timer datareceived event
    ''' </summary>
    Private Sub Timer1_Tick(ByVal sender As System.Object, _
                            ByVal e As System.EventArgs) Handles Timer1.Tick
        picDataReceived.BackColor = Color.Gray
        Timer1.Enabled = False
    End Sub

econdary thread ''' Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _ ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _ Handles SerialPort1.DataReceived ...

    End Sub

    Public Sub DoUpdate(ByVal sender As Object, ByVal e As System.EventArgs)

...

    End Sub

    .....

End Class

The original code is found here: https://code.msdn.microsoft.com/windowsapps/SerialPort-Sample-in-VBNET-fb040fb2

I've modified the code to suit my needs and am seeing the error "Index was outside the bounds of the array" when I run the application from the Debug folder on a separate PC (the files work with no flaws on my PC with Visual Studio). I thought the issue was with my modification, but it looks like the original file cannot be run. I have attempted to initialize the ints "Bytenumber" and "ByteToRead" with a value of 1, bit I still the issue. What could be causing it?

The exception text is:

************** Exception Text **************
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at LMUEngineering.mainForm.Form1_Load(Object sender, EventArgs e) in C:\Users\---\OneDrive\frmMain.vb:line 38
   at System.EventHandler.Invoke(Object sender, EventArgs e)
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
scimaks
  • 153
  • 1
  • 3
  • 12
  • 1
    You post the entire code (even the parts that are most likely not relevant) and can't even tell us what line the error is on? – Tim Jul 22 '15 at 17:01
  • possible duplicate of [What is IndexOutOfRangeException and how do I fix it?](http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it) – Adriano Repetti Jul 22 '15 at 17:02
  • The code compiles and runs on my development machine with no issues. When I run the application from the Debug/Release folders on another machine, I see the exception. I'm not sure where the error is occurring - otherwise I'd post relevant line numbers. – scimaks Jul 22 '15 at 17:02
  • 1
    In this case it will for sure crash when there aren't ports. Close() does not end method, just close form when it ends – Adriano Repetti Jul 22 '15 at 17:04
  • Looks like that's exactly the issue. Thank you very much Adriano! Are you able to post this as an answer? I will mark it as accepted. – scimaks Jul 22 '15 at 17:08
  • 1
    And btw I'd also move serial IO to a separate thread – Adriano Repetti Jul 22 '15 at 17:08
  • You may close as duplicate of linked one, more or less it's always same issue for this exception... – Adriano Repetti Jul 22 '15 at 17:11
  • 1
    Note that an array that has zero members is not Nothing. `Dim portNames as String()` - portNames is Nothing; `Dim portNames As String() = {}` - portNames is not Nothing (this would be your case when there are no serial ports). You may want to test the length of the array `If portNames.Length = 0 Then` – Blackwood Jul 22 '15 at 17:16

0 Answers0