Link to home
Start Free TrialLog in
Avatar of wellso
wellsoFlag for United Kingdom of Great Britain and Northern Ireland

asked on

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
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gruff82
Gruff82

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)
Avatar of wellso

ASKER

Thaks for the help
Glad to help :-)