Object reference not set to an instance of an object.

kevinheeney

Newcomer
Joined
Jun 24, 2003
Messages
20
VB.NET

I am trying to draw lines on my form.

I have a class called LineStuff and in the declarations at the top I am calling it:

Public mylines(999) As LineStuff
Public newestline as integer = 0

As a test I simply have form load setting the properties of mylines(newestline).X1 ,x2,y1,y2 etc.. At current in app newest line is always 0 I haven't added the step up yet.

Then I have the form Paint procedure.

With


'---------------


Dim g As Graphics = e.Graphics
Dim q As Integer = 0
Dim mypen As New Pen(Color.Black, 1)
mylines(q) = New LineStuff





Do
If mylines(q).X1 = 0 Or mylines(q).X2 = 0 Or mylines(q).Y1 = 0 Or mylines(q).Y2 = 0 Then Exit Do

g.DrawLine(mypen, mylines(q).X1, mylines(q).Y1, mylines(q).X2, mylines(q).Y2)
If newestline = 0 Then
Exit Do
Else
q += 1
End If

Loop Until q > newestline


When I run it, it gets to the paint event through a timer [[Invalidate()]] but will not access the class.

When it tries to access mylines it says.

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication2.exe

Additional information: Object reference not set to an instance of an object.

Does anybody have any suggestions. I am just now switching from VB6 to .NET
 
The only item in the array that is being created is in the line
Visual Basic:
 mylines(q) = New LineStuff

where q = 0.
the loop starts with q=0 but then increments it. As soon as q=1 mylines(q) is the same as mylines(1) which is uninitialised.
 
you could change the line
Visual Basic:
mylines(q) = New LineStuff

to something like
Visual Basic:
dim i as interger
for i = 0 to 999
    mylines(i) = new LineStuff
next

this would pre-create all 1000 items. This may be a bit heavy on memory unless you knew that you would always need 1000 items in the array.
 
Back
Top