Simple Graphics Problem

  • Thread starter Thread starter Timothy Taylor
  • Start date Start date
T

Timothy Taylor

Hello,

When i run these two lines of code i get an error saying "An unhandled
exception of type 'System.NullReferenceException' occurred in Object
Test.exe Additional information: Object reference not set to an instance of
an object."

This is the two lines of code that it runs:

Dim mygraphics As Graphics
mygraphics.DrawLine(New Pen(Color.Black), 1, 2, 3, 4)

It has that error on the second line of course. What am i doing wrong?

Thanks,

-Tim
 
To draw on a form/control you will need to override the OnPaint method. One
of the arguments passed to the PaintEventHandler is the valid graphics
object for that control which you can then use to draw onto the controls
surface:-
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)

e.Graphics.DrawLine(New Pen(Color.Black), 1, 2, 3, 4)

MyBase.OnPaint(e)


End Sub



Peter
 
You can also create a graphics object from the form if you wan;

Dim g As Graphics = Me.CreateGraphics()

Just be sure to dispose it when you are finished

g.Dispose()

Dan Fergus
MVP

Dim myGraphics As Graphics = new Graphic
 
Just like all versions of VB before .NET, simply decalring an object doesn't
create one. If this were a generic class, you'd need to do something like
this:

Dim mygraphics As New Graphics

Now the Graphics object is special in that it has no public constructor, so
you can only get one by having another class create it for you, such as in
the OnPaint method.
 
Back
Top