[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 324
  • Last Modified:

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
0
wellso
Asked:
wellso
  • 2
1 Solution
 
CodeCruiserCommented:
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

Featured Post

Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now