Handling DataReceived From Array/List of IO.SerialPort

I am refactoring a problem in VB.net that runs on one of our servers. Its role is to take input from barcode scanners connected to various virtual com ports and put the input to a database. Beofre there was 40 or so SerialPort components in the application; but now I am creating them dynamically into a array like this:

            
Dim PortList As New List(Of IO.Ports.SerialPort)

While x < rc
                PortList.Add(New IO.Ports.SerialPort)
                PortList(x).PortName = dset.Tables(0).Rows(x)("portname")
                PortList(x).ReadTimeout = 1500
                Try
                    PortList(x).Open()
                    For Each cCont As Label In gbStations.Controls
                        If cCont.Name = "Label" & CStr(x + 1) Then
                            cCont.BackColor = Color.Green
                        End If
                    Next cCont
                Catch ex As Exception
                    MsgBox(ex.Message)
                    For Each cCont As Label In gbStations.Controls
                        If cCont.Name = "Label" & CStr(x + 1) Then
                            cCont.BackColor = Color.Red
                        End If
                    Next cCont

                End Try
                x = x + 1

Open in new window


What I want to do know is convert the fuicntion that recieves the data to use this array of ports for the DataReceived evetn. Before it was something like this

Public Sub getData (ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived, SerialPort2.DataReceived, SerialPort3.DataReceived etc.

Open in new window


Can anyone explain to me how to handle the DataReceived events dynamically? Thanks
LVL 2
wellsoAsked:
Who is Participating?
 
CodeCruiserConnect With a Mentor Commented:
Remove the

Handles SerialPort1.DataReceived, SerialPort2.DataReceived, SerialPort3.DataReceived etc.

bit from the method

and add

AddHandler PortList(x).DataReceived, Addressof getData

in the loop.
0
 
Gruff82Commented:
When you are creating your ports use a lambada delegate

var port = new  IO.Ports.SerialPort
port.DataReceived += (s,e) => { //perform your event code here }
port.PortName = dset.Tables(0).Rows(x)("portname")

PortList.Add(port)
0
 
wellsoAuthor Commented:
Thaks for the help
0
 
CodeCruiserCommented:
Glad to help :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.