Text Drawing Error! Please Help!!

When trying to run this code, i get the error: System.NullReferenceException was unhandled.

My Code (Very Simple):

Public Class form1

Dim paints As System.Drawing.Graphics

Dim afont As New System.Drawing.Font("Arial", 22, FontStyle.Regular)

Dim x As Integer = 10

Dim y As Integer = 10

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

'This Doesn't Work!

paints.DrawString("Arctic Games Programming", afont, Brushes.Black, x, y)

End Sub

Private Sub form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

'This Code Works

e.Graphics.DrawString("Arctic Games Programming", afont, Brushes.Black, x, y)

End Sub

End Class



Answer this question

Text Drawing Error! Please Help!!

  • Albert Pinto

    Lol, true. . .
  • steve_flavel

    In your code the variable paints is never being set to a valid Graphics object, in the load function you could simply insert a line previously of:

    paints = Graphics.FromHwnd(Me.Handle)

    While this will not break at runtime it will also be effectively worthless as your form1_Load method is firing before the form is ever being drawn and when it is drawn your previous drawing is lost and then redrawn again from form1_Paint.



  • JustinRenquist

    In the Load event handler, the paints object isn't initialized. You could do this with:
    paints = Me.CreateGraphics()

    That's not necessary though, the Paint event handler will take care of painting.



  • Hassaan

    You have it right (correct) by going through the paint method. For simple text, then the label may be the way to go.....

  • Fortes

    You could put a label control on the form...



  • Bigcheesegs

    Is there an easier way to do something like this I just want it to display the text when it loads and maybe animate by changing the values of x and y
  • Text Drawing Error! Please Help!!