I have a Visual Basic .Net program which is throwing an error I dont know how to fix

This was a working program and still works most of the time. When certain strings are entered into textbox1 I get an error. Other strings work fine

This string works:
%B6014235004461889=000202916=JEFF/SCHASNY=100390200000?;6014235004461889=49121010000001

This one doesn't:
%bB6014235005191880=105812961=RAVEN/ALONSO=100697765000?6014235005191880=49121010000001


Error message:

System.NullReferenceException: Object reference not set to an instance of an object.
   at PrintBookList.Form1.TextBox1_KeyPress(Object sender, KeyPressEventArgs e)
   at System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
   at System.Windows.Forms.Control.WmKeyChar(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)


Code:

Public subr As UniSubroutine
    Public CtlFile As UniFile
    Public TxRowFile As UniFile
    Public isbnlist As UniDynArray
    Public coursedesclist As UniDynArray
    Public authlist As UniDynArray
    Public titlelist As UniDynArray
    Public reqoptlist As UniDynArray
    Public conclist As UniDynArray
    Public noadoptlist As UniDynArray
    Public choicelist As UniDynArray
    Dim pline As String = ""
    Dim ThisTerm As String = ""
    Dim ThisTermDesc As String = ""
    Dim e As String = ""
    Dim sender As Object = ""



    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'make this application run full screen with no boarder
        'Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedToolWindow
        'Me.WindowState = FormWindowState.Maximized

        TextBox1.Focus()

    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

        If e.KeyChar = Chr(13) Then

            Dim scan As String = ""
            scan = TextBox1.Text
            TextBox1.Text = ""
jeff15Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
you surely have other code!
0
jeff15Author Commented:
Sure, here's the whole thing:

' imports for raw printing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices

Public Class Form1

    Public sess As UniSession
    Public subr As UniSubroutine
    Public CtlFile As UniFile
    Public TxRowFile As UniFile
    Public isbnlist As UniDynArray
    Public coursedesclist As UniDynArray
    Public authlist As UniDynArray
    Public titlelist As UniDynArray
    Public reqoptlist As UniDynArray
    Public conclist As UniDynArray
    Public noadoptlist As UniDynArray
    Public choicelist As UniDynArray
    Dim pline As String = ""
    Dim ThisTerm As String = ""
    Dim ThisTermDesc As String = ""
   



    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' make this application run full screen with no boarder
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedToolWindow
        Me.WindowState = FormWindowState.Maximized

        TextBox1.Focus()

    End Sub


    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

        If e.KeyChar = Chr(13) Then

            Dim scan As String = ""
            scan = TextBox1.Text
            TextBox1.Text = ""

            ' open the Unisession
            Try
                sess = UniObjects.OpenSession("vr, "1local", "cust", "/u1/local", "uvcs")
            Catch ex As Exception
                MsgBox("Cannot open UniObjects Session Error = " & ex.Message)
                TextBox1.Focus()
            End Try

            'open the CONTROL file
            Try
                CtlFile = sess.CreateUniFile("CONTROL")
            Catch ex As Exception
                MsgBox("Cannot open the CONTROL file")
                TextBox1.Focus()
            End Try

            'Read the CONTROL record containing the current term and description
            Try
                CtlFile.Read("PRINT.BOOK.LIST")
            Catch ex As Exception
                MsgBox("CONTROL File read failed - " & ex.Message)
                TextBox1.Focus()
            End Try

            'open the TX.ROW file
            Try
                TxRowFile = sess.CreateUniFile("TX.ROW")
            Catch ex As Exception
                MsgBox("Cannot open the TX.ROW file")
                TextBox1.Focus()
            End Try


            ThisTerm = CtlFile.Record.Extract(1).ToString
            ThisTermDesc = CtlFile.Record.Extract(2).ToString

            Dim errmsg As String = ""
            Dim custname As String = ""
            Dim vals As Int32
            Dim valstr As String
            Dim noadoptcount As Int32 = 0
            Dim noadoptstr As String
            Dim strHostName As String
            Dim choicecount As Int32 = 0
            Dim choicestr As String
            ' hostname gets passed to the server to tag the swipe tracking record
            strHostName = System.Net.Dns.GetHostName()

            ' call the subroutine to get the book list
            subr = sess.CreateUniSubroutine("GET.STUDENT.COURSES", 21)
            subr.SetArg(0, scan)
            subr.SetArg(1, ThisTerm)
            subr.SetArg(2, "")
            subr.SetArg(3, "")
            subr.SetArg(4, "")
            subr.SetArg(5, "")
            subr.SetArg(6, "")
            subr.SetArg(7, "")
            subr.SetArg(8, "")
            subr.SetArg(9, "")
            subr.SetArg(10, "")
            subr.SetArg(11, "")
            subr.SetArg(12, "")
            subr.SetArg(13, "")
            subr.SetArg(14, "")
            subr.SetArg(15, "")
            subr.SetArg(16, "")
            subr.SetArg(17, "")
            subr.SetArg(18, strHostName)
            subr.SetArg(19, "")
            subr.SetArg(20, "")

            subr.Call()

            authlist = subr.GetArgDynArray(16)
            titlelist = subr.GetArgDynArray(17)

            coursedesclist = subr.GetArgDynArray(8)
            reqoptlist = subr.GetArgDynArray(9)
            isbnlist = subr.GetArgDynArray(10)
            valstr = subr.GetArg(11)
            vals = Convert.ToInt32(valstr)
            noadoptstr = subr.GetArg(15)
            noadoptcount = Convert.ToInt32(noadoptstr)
            noadoptlist = subr.GetArgDynArray(14)
            choicestr = subr.GetArg(20)
            choicecount = Convert.ToInt32(choicestr)
            choicelist = subr.GetArgDynArray(19)


            errmsg = subr.GetArg(12)
            custname = subr.GetArg(13)

            If errmsg <> "" Then
                'if the program returns an error message then print it
                pline = vbCrLf & vbCrLf & vbCrLf & vbCrLf & ThisTermDesc & vbCrLf & custname & vbCrLf & vbCrLf & vbCrLf & errmsg & vbCrLf & vbCrLf & vbCrLf & vbCrLf & Chr(27) & "i" & vbCrLf
                RawPrinterHelper.SendStringToPrinter("Generic", pline)
                TextBox1.Text = ""
                TextBox1.Focus()
            Else
                'print the booklist
                Dim ndx As Integer
                Dim roflag As String
                Dim roout As String = ""
                Dim cutstr As String = Chr(27) & "i"
                Dim boldstr As String = Chr(27) & "!" & Chr(8)
                Dim fontstr As String = Chr(27) & "!" & Chr(0)
                Dim dblstr As String = Chr(27) & "!" & Chr(24)
                pline = boldstr & "  " & ThisTermDesc & vbCrLf & "Customer ID " & custname & vbCrLf & vbCrLf
                pline = pline & "We receive course enrollment data once" & vbCrLf & "per day so the information below" & vbCrLf & "may be up to 24 hours old." & vbCrLf & "If you have recently added/dropped courses" & vbCrLf & "please use MyCUInfo for a complete list."
                pline = pline & vbCrLf & vbCrLf & "This list may not contain all books" & vbCrLf & "for all courses if we have not" & vbCrLf & "received that information from" & vbCrLf & "your professors." & vbCrLf & vbCrLf

                For ndx = 1 To vals
                    Dim author As String = ""
                    Dim title As String = ""
                    Dim isbn As String = ""
                    Dim txrow As String = ""

                    roflag = reqoptlist.Extract(ndx).StringValue

                    Select Case roflag
                        Case "O"
                            roout = "Optional"
                        Case "R"
                            roout = "Required"
                        Case "B"
                            roout = "Bookstore Recommended"
                        Case "RX"
                            roout = "Required - See Choices Below"
                    End Select


                    author = authlist.Extract(ndx).StringValue
                    title = titlelist.Extract(ndx).StringValue
                    isbn = isbnlist.Extract(ndx).StringValue

                    'Read the TX.ROW record containing the current row location for this isbn
                    Try
                        TxRowFile.Read(isbn)
                    Catch ex As Exception
                        txrow = ""
                    End Try

                    txrow = TxRowFile.Record.Extract(1).ToString


                    If author = "NTR" Then
                        roout = "No Textbook Required For This Course"
                    End If

                    pline = pline & boldstr & "Author: " & author & vbCrLf
                    pline = pline & "Title: " & title & vbCrLf

                    pline = pline & coursedesclist.Extract(ndx).StringValue & vbCrLf
                    pline = pline & boldstr & roout & boldstr & vbCrLf

                    If txrow <> "" Then
                        pline = pline & boldstr & "Row " & txrow & boldstr & vbCrLf
                    End If
                    pline = pline & isbn & vbCrLf & " " & vbCrLf

                Next ndx

                ' courses with no adoptions
                If noadoptcount > 0 Then
                    pline = pline & boldstr
                    pline = pline & "We have not yet received book" & vbCrLf & "information from your professors" & vbCrLf & "for the following courses:" & vbCrLf & vbCrLf
                    pline = pline & boldstr
                    For ndx = 1 To noadoptcount
                        pline = pline & noadoptlist.Extract(ndx).StringValue & vbCrLf
                    Next
                End If

                ' choices
                If choicecount > 0 Then
                    pline = pline & vbCrLf & "     C H O I C E S " & vbCrLf
                    pline = pline & boldstr
                    For ndx = 1 To choicecount
                        pline = pline & choicelist.Extract(ndx).StringValue & vbCrLf
                    Next
                End If

                pline = pline & vbCrLf & " " & vbCrLf & " " & vbCrLf & " " & vbCrLf & " " & vbCrLf & " " & vbCrLf & Chr(27) & "i" & vbCrLf

                RawPrinterHelper.SendStringToPrinter("Generic", pline)

            End If ' errmsg
                ' always close the session
                UniObjects.CloseSession(sess)
        End If ' chr(13)

        TextBox1.Focus()
    End Sub
   
 
End Class

'copy this whole class into anything needing raw printing
Public Class RawPrinterHelper
    ' Structure and API declarions:
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Structure DOCINFOW
        <MarshalAs(UnmanagedType.LPWStr)> Public pDocName As String
        <MarshalAs(UnmanagedType.LPWStr)> Public pOutputFile As String
        <MarshalAs(UnmanagedType.LPWStr)> Public pDataType As String
    End Structure

    <DllImport("winspool.Drv", EntryPoint:="OpenPrinterW", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function OpenPrinter(ByVal src As String, ByRef hPrinter As IntPtr, ByVal pd As Long) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="ClosePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="StartDocPrinterW", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function StartDocPrinter(ByVal hPrinter As IntPtr, ByVal level As Int32, ByRef pDI As DOCINFOW) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="EndDocPrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function EndDocPrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="StartPagePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function StartPagePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="EndPagePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function EndPagePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function
    <DllImport("winspool.Drv", EntryPoint:="WritePrinter", _
       SetLastError:=True, CharSet:=CharSet.Unicode, _
       ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Public Shared Function WritePrinter(ByVal hPrinter As IntPtr, ByVal pBytes As IntPtr, ByVal dwCount As Int32, ByRef dwWritten As Int32) As Boolean
    End Function

    ' SendBytesToPrinter()
    ' When the function is given a printer name and an unmanaged array of  
    ' bytes, the function sends those bytes to the print queue.
    ' Returns True on success or False on failure.
    Public Shared Function SendBytesToPrinter(ByVal szPrinterName As String, ByVal pBytes As IntPtr, ByVal dwCount As Int32) As Boolean
        Dim hPrinter As IntPtr      ' The printer handle.
        Dim dwError As Int32        ' Last error - in case there was trouble.
        Dim di As DOCINFOW          ' Describes your document (name, port, data type).
        Dim dwWritten As Int32      ' The number of bytes written by WritePrinter().
        Dim bSuccess As Boolean     ' Your success code.

        ' Set up the DOCINFO structure.
        With di
            .pDocName = "My Visual Basic .NET RAW Document"
            .pDataType = "RAW"
        End With
        ' Assume failure unless you specifically succeed.
        bSuccess = False
        If OpenPrinter(szPrinterName, hPrinter, 0) Then
            If StartDocPrinter(hPrinter, 1, di) Then
                If StartPagePrinter(hPrinter) Then
                    ' Write your printer-specific bytes to the printer.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, dwWritten)
                    EndPagePrinter(hPrinter)
                End If
                EndDocPrinter(hPrinter)
            End If
            ClosePrinter(hPrinter)
        End If
        ' If you did not succeed, GetLastError may give more information
        ' about why not.
        If bSuccess = False Then
            dwError = Marshal.GetLastWin32Error()
        End If
        Return bSuccess
    End Function ' SendBytesToPrinter()

    ' SendFileToPrinter()
    ' When the function is given a file name and a printer name,
    ' the function reads the contents of the file and sends the
    ' contents to the printer.
    ' Presumes that the file contains printer-ready data.
    ' Shows how to use the SendBytesToPrinter function.
    ' Returns True on success or False on failure.
    Public Shared Function SendFileToPrinter(ByVal szPrinterName As String, ByVal szFileName As String) As Boolean
        ' Open the file.
        Dim fs As New FileStream(szFileName, FileMode.Open)
        ' Create a BinaryReader on the file.
        Dim br As New BinaryReader(fs)
        ' Dim an array of bytes large enough to hold the file's contents.
        Dim bytes(fs.Length) As Byte
        Dim bSuccess As Boolean
        ' Your unmanaged pointer.
        Dim pUnmanagedBytes As IntPtr

        ' Read the contents of the file into the array.
        bytes = br.ReadBytes(fs.Length)
        ' Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(fs.Length)
        ' Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, fs.Length)
        ' Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, fs.Length)
        ' Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes)
        Return bSuccess
    End Function ' SendFileToPrinter()

    ' When the function is given a string and a printer name,
    ' the function sends the string to the printer as raw bytes.
    Public Shared Function SendStringToPrinter(ByVal szPrinterName As String, ByVal szString As String)
        Dim pBytes As IntPtr
        Dim dwCount As Int32
        ' How many characters are in the string?
        dwCount = szString.Length()
        ' Assume that the printer is expecting ANSI text, and then convert
        ' the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString)
        ' Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount)
        Marshal.FreeCoTaskMem(pBytes)
    End Function
End Class
0
Éric MoreauSenior .Net ConsultantCommented:
now it is too long! can't you run the code in the IDE and tell us on which line it is breaking?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jacques Bourgeois (James Burger)PresidentCommented:
Compare this portion of the string that works

     100390200000?;6014235004461889

with the one that does not work

     100697765000?6014235005191880

There appears to be a semi-colon missing after the question mark in the second one. This might cause something down the execution path behave in a different way (maybe it does not find something it is looking for) and return Nothing instead of the expected result.
0
jeff15Author Commented:
I found the solution to my problem while running the program in the debugger. The error message I was getting had nothing to do this the actual error which was 20+ lines below. Thanks to Éric Moreau for suggesting I run it in debug.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

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.