Draw a line on a TabPage in C#

3.9k views Asked by At

I am having trouble drawing a line on a TabPage.

I actually have a TabControl inside a TabControl. I have drawn a number of labels which I am using as boxes. I want to draw lines to join them together.

I have tried:

Pen P = new Pen(System.Drawing.Color.Black, 10);
tabname.CreateGraphics().DrawLine(P, 10, 10, 100, 100);

and

Pen P = new Pen(System.Drawing.Color.Black, 10);            
tabcontrolname.TabPages[0].CreateGraphics().DrawLine(P, 10, 10, 100, 100);

Neither are displaying the line. I assume the line is being placed somewhere as there are no errors.

Any ideas how I can get it to display on the correct TabPage?

Thank you!

3

There are 3 answers

2
RHodgett On

I was able to get the arrow to show up using the following code:

TabPage.Paint += new PaintEventHandler(TabPage_Paint);

and

        protected void TabPage_Paint(object sender, PaintEventArgs e)
    {
        base.OnPaint(e);
        Pen arrow = new Pen(Brushes.Black, 4);
        arrow.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;

        e.Graphics.DrawLine(arrow, 10, 10, 100, 100);
        arrow.Dispose();
    }

However, when scrolling is initiated the Paint messes up :(

0
Waylon Flinn On

You probably need to override the OnPaint method (or handle the Paint event) to get this to work properly. If you don't your controls will just end up drawing over your lines.

Here's a link to the relevant docs.

0
tafa On

Where do you try these codes, in which function? If you are doing it once in the initialization or construction, they will not be displayed as you expect. Whenever the control needs to be redrawn, you need to draw this line too, again. Either override the OnPaint method of the control or register for the Paint event and do the line drawing there.