Problem in DrawLine

dhj

Well-known member
Joined
Sep 18, 2003
Messages
82
Location
Sri Lanka
In one form of my VB.NET Windows application, I have a picturebox. I need to draw a line (using known coordinates) on picturebox when the form is loading. Following is the code I wrote in my Form_Load event.

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

PictureBox1.Refresh()

Dim g As Graphics = CType( PictureBox1, PictureBox).CreateGraphics

Dim myPen As New Pen(Color.Red)
myPen.Width = 2

g.DrawLine(myPen, 0, 0, 100, 100)

myPen.Dispose()
g.Dispose()

End Sub


But its not displaying the Line when the Form is loading. I cannot figure out why.

Thank you
 
I tried you code and as you say it does not work, I suspect this is because you are using the load event to draw and the timing is such that the line is rubbed out before the form is properly loaded.
You should do all you drawing in the paint event so:
Code:
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint

        Dim myPen As New Pen(Color.Red)
        myPen.Width = 2

        e.Graphics.DrawLine(myPen, 0, 0, 100, 100)
        myPen.Dispose()


    End Sub

Notice I am using the graphics object supplied by the paint event, do not use CreateGraphics!

Hope this helps
 
Quite right, the .Load event is called immediately BEFORE the form is shown for the first time. Any drawing you do before the form is shown will never show up.
Also, FYI, the pen constructor has an overload like this (color As System.Drawing.Color, width As Single).
 
Back
Top