dunkleosteus
dunkleosteus

Reputation: 336

System.Drawing.Pen - lines disappear when Labels are placed on Form

I want to draw TextBoxes/Labels on my form in code and connect them with lines - based on data that I have stored in a datatable ("treedata"). If I use the following code everything works fine:

    For i = 0 To treedata.Rows.Count - 1

        Dim tb As New TextBox

        hor = treedata.Rows(i)(11)
        vern = ver + 120 * treedata.Rows(i)(4)

        tb.Text = "sometext"
        tb.Location = New Point(hor, vern)

        Form8.Controls.Add(tb)

        posofmodif = treedata.Rows(i)(10)
        vero = treedata.Rows(i)(6)

        Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Green)
        Dim formGraphics As System.Drawing.Graphics

        myPen.SetLineCap(LineCap.RoundAnchor, LineCap.ArrowAnchor, DashCap.Flat)
        formGraphics = Form8.CreateGraphics()
        formGraphics.DrawLine(myPen, Convert.ToSingle(posofmodif), Convert.ToSingle(vero), Convert.ToSingle(hor), Convert.ToSingle(vern))

        myPen.Dispose()
        formGraphics.Dispose()

    Next

However I would like to use labels instead of TextBoxes because it makes no sense to use heavier TextBoxes in this case. But when I simply replace

Dim tb As New TextBox

by

Dim tb As New Label

the labels do appear on the Form as expected but the lines connecting them appear only for a moment and then turn invisible.

I first thought that the problem might be caused by labels being over or below the lines but even when I make sure that no line is crossing any label it happens.

Does anyone have an idea what I could do to avoid this?

Upvotes: 1

Views: 257

Answers (1)

DonBoitnott
DonBoitnott

Reputation: 11025

This is your problem: Form8.CreateGraphics(). That method is volatile, as it creates a Graphics instance that does not survive the scope in which it's used.

You need to be using the Paint event for whatever control on which you intend to draw. The form, the label...whatever that is. The Paint event provides a Graphics object for you to use, and it gets called whenever the drawing needs to be refreshed.

Because the event fires frequently, you need to be mindful of what you do there. Heavy lifting in a Paint handler can slow an app down considerably.

Upvotes: 3

Related Questions