Solved

Object reference not set

Posted on 2009-05-06
8
427 Views
Last Modified: 2013-11-26
Im trying to read a COM port to see if something has come across itI get an error on this line of code:

btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})

saying that object reference not set to an instance of an object?
Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialCOMDiscover.DataReceived

        btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})

    End Sub

    'This sub will read the COMport and populate the Discovery Grid to list all active Wireless Gauge in Range.

    Public Sub UpdateGrid()
 

        tempArray = strDataCOM1.Split(New Char() {Chr(13)}, StringSplitOptions.RemoveEmptyEntries)

        If tempArray.Length = 0 Then

            Exit Sub

        ElseIf tempArray.Length < 10 Then

            Exit Sub

        ElseIf GageID_Discovery = False Then

            Dim String1 As String = strDataCOM1

            GageID = String1.Substring(String1.IndexOf("L0"), String1.Substring(String1.IndexOf("L0")).IndexOf(" "))

            GageID = GageID.Replace(vbCrLf, vbTab).Replace(Chr(26), "").Replace(Chr(12), "").Replace(Chr(13), "")

            GageID_Discovery = True

            serialCOMDiscover.DiscardInBuffer()

            Me.btnDiscover.Enabled = True

            Me.GridSpread.Enabled = True
 

        Else

            Me.tmrDiscover.Enabled = False

            Me.GridSpread.ActiveSheet.SetValue(0, 0, tempArray(3))

            Me.GridSpread.ActiveSheet.SetValue(0, 2, tempArray(4))

            Me.GridSpread.ActiveSheet.SetValue(0, 1, tempArray(5))

            Me.GridSpread.ActiveSheet.SetValue(0, 3, tempArray(8))

            Me.GridSpread.ActiveSheet.SetValue(0, 4, tempArray(7))

        End If

        Array.Clear(tempArray, 0, tempArray.Length)

    End Sub

Open in new window

0
Comment
Question by:cmdolcet
  • 4
  • 3
8 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24316728
Well...the only object that couldn't possibly bet set is "btnDiscover"...

Is the error by chance happening when the form first loads but before it is displayed?

You could explicitly check with:

    Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialCOMDiscover.DataReceived
        If Not IsNothing(btnDiscover) Then
            btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})
        End If
    End Sub
0
 

Author Comment

by:cmdolcet
ID: 24318644
No I still get the error
 Private Sub btnDiscover_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiscover.Click

        Try

            Me.tmrDiscover.Enabled = True

            ReadOutWirelessInformation()

        Catch ex As Exception

            WirelessDevice.Text = "Wireless Signal: No Gauges in range can be found"

        End Try
 

    End Sub

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24318708
Same line?  Can you post the code for ReadOutWirelessInformation()?
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:cmdolcet
ID: 24318733
Here is that code!
  Private Sub ReadOutWirelessInformation()

        Try

            serialCOMDiscover.Write("<@:L" & GageID & "06<INFO>")

        Catch ex As Exception

            MessageBox.Show("Requested Serial String was incorrectly sent to wireless device")

        End Try

    End Sub

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 24318844
Can you post the whole thing?
0
 

Author Comment

by:cmdolcet
ID: 24318871
yes I will
Imports System.IO.Ports

Imports System.Windows.Forms

Imports System.Threading

Imports System.math

Public Class frmSearch

#Region " Form Variables"
 

    Public WirelessCOM1Values As New ArrayList

    Public Delegate Sub myDelegate()

    Public Discover_Press As Boolean = False

    Public GageID_Discovery As Boolean = False

    Public WithEvents serialCOMDiscover As New IO.Ports.SerialPort

    Public B(7) As Byte

    Public output(2) As Byte

#End Region
 

    'Discovers Indicator COM Port

#Region "Indicator COM Port Discovery"

    'API Declarations

    Public Declare Function CreateFile Lib "kernel32.dll" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long

    Public Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long

    Public Structure SECURITY_ATTRIBUTES

        Dim nLength As Long

        Dim lpSecurityDescriptor As Long

        Dim bInheritHandle As Long

    End Structure

    'API constants

    Public Const FILE_SHARE_READ = &H1

    Public Const FILE_SHARE_WRITE = &H2

    Public Const OPEN_EXISTING = 3

    Public Const FILE_ATTRIBUTE_NORMAL = &H80

    'Return TRUE if the COM exists, FALSE if the COM does not exist

    Public Function COMAvailable(ByVal COMNum As Integer) As Boolean

        Dim hCOM As Long

        Dim ret As Long

        Dim sec As SECURITY_ATTRIBUTES
 

        'try to open the COM port

        hCOM = CreateFile("COM" & COMNum & "", 0, FILE_SHARE_READ + FILE_SHARE_WRITE, sec, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)

        If hCOM = -1 Then

            COMAvailable = False

        Else

            COMAvailable = True

            'close the COM port

            ret = CloseHandle(hCOM)

        End If

    End Function

    Public Sub DiscoverIndicatorCOMPort()

        Dim result As MsgBoxResult

        Dim strMessage As String

        ActiveCOM.Clear()

        Try

            Dim myWMIClassSearcher As New Management.ManagementObjectSearcher("root\cimv2", "SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%(COM%'") 'Get all Serial Ports

            Dim myPorts As Management.ManagementObjectCollection = myWMIClassSearcher.Get()

            'Cycle throug all COM ports on local PC

            For Each myPort As Management.ManagementObject In myPorts

                If myPort.GetPropertyValue("Name") = "Communications Port (COM1)" Then
 

                End If
 

                IndicatorCOMPort = myPort.GetPropertyValue("Name")

                Dim myStrings()

                myStrings = Strings.Split(IndicatorCOMPort)

                IndicatorCOMPort = myStrings(3).Trim("("c, ")"c, Chr(34))

                IndicatorCOMPort = IndicatorCOMPort.Trim("C", "O", "M")

                ActiveCOM.Add(IndicatorCOMPort)

                'Exit For

            Next

        Catch ex As Exception

            strMessage = "No COM Ports Discovered:" & vbCrLf & vbCrLf & "Select [ Yes ] rediscover COM Ports:" & vbCrLf & vbCrLf & "Select [ No ] To exit" & vbCrLf

            result = MsgBox(strMessage, MsgBoxStyle.Information + MsgBoxStyle.YesNo, "")

            If result = MsgBoxResult.Yes Then

                DiscoverIndicatorCOMPort()

            ElseIf result = MsgBoxResult.No Then

                Me.Close()

            End If

        End Try

    End Sub
 
 

#End Region
 

    'Currently this is hard set to COM 1 and Baudrate is at 9600

#Region " COM Port Setup"

    Public Sub SerialPortCOMControl()

        Try

            If IsNothing(serialCOMDiscover) Then

                serialCOMDiscover = New IO.Ports.SerialPort

            End If

            'set the properties of the com port

            serialCOMDiscover.PortName = "COM1"

            serialCOMDiscover.BaudRate = 57600

            serialCOMDiscover.Parity = Parity.None

            serialCOMDiscover.DataBits = 8

            serialCOMDiscover.RtsEnable = True

            serialCOMDiscover.Open()

            SerialPortStatus.Text = "Connection Status: " & " COM Port Enabled"

            ConnectionStatus.BackColor = System.Drawing.Color.LightGreen

        Catch ex As Exception

            SerialPortStatus.Text = "Connection Status: " & " COM Port NOT Enabled"

            ConnectionStatus.BackColor = System.Drawing.Color.Red

        End Try

    End Sub

#End Region
 

    'Form timers

#Region "Form Timers"

    'This trmDiscover Timer will only fire if a gauge has not been dsicovered in 5 secs.

    Private Sub tmrDiscover_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDiscover.Tick

        Me.tmrDiscover.Enabled = False

        ' Dim msg As MessageBoxButtons

        MessageBox.Show("No Gauges could be found.!", "Wireless Signal", MessageBoxButtons.OK)

        WirelessDevice.Text = "Wireless Signal: No Gauges in range can be found"

        ConnectionStatus.BackColor = System.Drawing.Color.Red

        SerialPortStatus.Text = "Connection Status: " & " COM Port Enabled"

        ConnectionStatus.BackColor = System.Drawing.Color.LightGreen

    End Sub

#End Region
 

    Private Sub btnDiscover_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiscover.Click

        Try

            Me.tmrDiscover.Enabled = True

            ReadOutWirelessInformation()

        Catch ex As Exception

            WirelessDevice.Text = "Wireless Signal: No Gauges in range can be found"

        End Try
 

    End Sub

    Private Sub frmSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Dim dlgSetupMode As New dlgSetModeNotice

        'dlgSetupMode.TopMost = True

        'dlgSetupMode.Focus()

        ' Me.Enabled = False

        'dlgSetupMode.Show()

        'DiscoverIndicatorCOMPort()

        SerialPortCOMControl()

        LoadPageVariables()

        serialCOMDiscover.Write("<RS")

        Me.GridSpread.Enabled = False

    End Sub

    'Is the initial command after the Discovery button is pressed that will request the INFO

    'from the Wireless Device

    Private Sub ReadOutWirelessInformation()

        Try

            serialCOMDiscover.Write("<@:L" & GageID & "06<INFO>")

        Catch ex As Exception

            MessageBox.Show("Requested Serial String was incorrectly sent to wireless device")

        End Try

    End Sub

    Private Sub DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialCOMDiscover.DataReceived

        If Not IsNothing(btnDiscover) Then

            btnDiscover.Invoke(New myDelegate(AddressOf UpdateGrid), New Object() {})

        End If

    End Sub

    'This sub will read the COMport and populate the Discovery Grid to list all active Wireless Gauge in Range.

    Public Sub UpdateGrid()
 

        tempArray = strDataCOM1.Split(New Char() {Chr(13)}, StringSplitOptions.RemoveEmptyEntries)

        If tempArray.Length = 0 Then

            Exit Sub

        ElseIf tempArray.Length < 10 Then

            Exit Sub

        ElseIf GageID_Discovery = False Then

            Dim String1 As String = strDataCOM1

            GageID = String1.Substring(String1.IndexOf("L0"), String1.Substring(String1.IndexOf("L0")).IndexOf(" "))

            GageID = GageID.Replace(vbCrLf, vbTab).Replace(Chr(26), "").Replace(Chr(12), "").Replace(Chr(13), "")

            GageID_Discovery = True

            serialCOMDiscover.DiscardInBuffer()

            Me.btnDiscover.Enabled = True

            Me.GridSpread.Enabled = True
 

        Else

            Me.tmrDiscover.Enabled = False

            Me.GridSpread.ActiveSheet.SetValue(0, 0, tempArray(3))

            Me.GridSpread.ActiveSheet.SetValue(0, 2, tempArray(4))

            Me.GridSpread.ActiveSheet.SetValue(0, 1, tempArray(5))

            Me.GridSpread.ActiveSheet.SetValue(0, 3, tempArray(8))

            Me.GridSpread.ActiveSheet.SetValue(0, 4, tempArray(7))

        End If

        Array.Clear(tempArray, 0, tempArray.Length)

    End Sub

    Private Sub GridSpread_CellDoubleClick(ByVal sender As Object, ByVal e As FarPoint.Win.Spread.CellClickEventArgs) Handles GridSpread.CellDoubleClick

        Me.Hide()

        serialCOMDiscover.Close()

        Dim frmGaugeInfo As New Form1

        frmGaugeInfo.Show()

    End Sub

    Private Sub LoadPageVariables()

        Me.lblSoftwareVersion.Text = Software_Version

        Me.lblFirmwareVersion.Text = "Version 3.2.0"

        Me.lblCOMPort.Text = serialCOMDiscover.PortName

        Me.lblBaudRate.Text = serialCOMDiscover.BaudRate

    End Sub

    Private Sub DiscoverModeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DiscoverModeToolStripMenuItem.Click

        serialCOMDiscover.Write("<RS")

    End Sub

    Private Sub EndDiscoverToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EndDiscoverToolStripMenuItem.Click

        serialCOMDiscover.Write("<RN")

    End Sub

    Private Sub ResetWirelessReceiverToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResetWirelessReceiverToolStripMenuItem.Click

        serialCOMDiscover.Write("<RN")

        serialCOMDiscover.Write("<RS")

    End Sub

End Class

Open in new window

0
 

Accepted Solution

by:
cmdolcet earned 0 total points
ID: 24355017
Idle_Mind, modus_operandi, I was able to find my answer as to why it was throwing the error. When I put the readline command in It didn;t throw the error again.
Can this be closed now?

Thanks
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Tool Box 2 34
scanning dentists xray (the small ones) 3 43
Help with AsEnumerable(), LINQ 4 22
What do you call this line of code in this .NET Core page? 4 24
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now