How to draw a line on panel? It is not showing up

Badmiral picture Badmiral · Dec 19, 2012 · Viewed 22.8k times · Source

I have a Panel called panel1 and I am trying to draw a line on my panel1 using this code:

var g = panel1.CreateGraphics();
var p = new Pen(Color.Black, 3);

var point1 = new Point(234,118);
var point2 = new Point(293,228);

g.DrawLine(p, point1, point2);

But nothing is showing up. Any ideas? This is in a windows form.

Answer

keyboardP picture keyboardP · Dec 19, 2012

Handle the Panel's Paint event and put it in there. What's happening is that it's being drawn once in the constructor but then being drawn over in the Paint event everytime it's called.

private void panel1_Paint(object sender, PaintEventArgs e)
{
    base.OnPaint(e);
    using(Graphics g = e.Graphics)
    {
       var p = new Pen(Color.Black, 3);
       var point1 = new Point(234,118);
       var point2 = new Point(293,228);
       g.DrawLine(p, point1, point2);
    }
}