Saturday, November 3, 2012

Error: object reference not set to an instance of an object in VB.NET

Error: object reference not set to an instance of an object in VB.NET


If you see this error, is because you forgot to use the NEW function and/or your object is set to nothing.
It happens a lot when you do some coding and you haven’t tested it a lot.

Or if your code builds some XML nodes or elements, sometimes, you forgot to think at 1 or 2 situations.
If you are starting to have a lot of these errors, maybe because you are mixing basic value type and object.

A String or an integer is to simple stuff and you may not have the famous error message: object reference not set to an instance of an object.
If you dealing with something more complex (System.object, Autodesk.MidDocument, SeeExpert.Application, Office.Document….) , then the message will comes if you don’t create it correctly before using it.


    Public Sub myFunction()
        Dim oForm_to_crash As Form
        oForm_to_crash.Show()
    End Sub



Do something like this next time. (See Example):


    Public Sub myFunction()
        Dim oForm_to_crash As Form
        oForm_to_crash = New Form ' Good : place the new here
        oForm_to_crash.Show()
    End Sub



Avoid this: (because you won’t be able to surround the error correctly with the try-catch-finally):


    Public Sub myFunction()
        Dim oForm_to_crash As New Form 'don't put the new here
        oForm_to_crash.Show()
    End Sub

Always try to use the try-catch in your code:

    Public Sub myFunction()
        Dim oForm_to_crash As Form 'don't put the new here
        Try
            oForm_to_crash = New Form
            oForm_to_crash.Show()
        Catch ex As Exception
            'something here
        Finally
            'something else here
        End Try

    End Sub


Next post : Multi Forms in VB.NET

Reference:



The program I love to use, buy it:


No comments:

Post a Comment