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

23,962

Solution 1

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);
    }
}

Solution 2

Put it in some event after the form has been created and shown on the screen and it should work fine.

It's best to put it in the Paint event, as keyboardP stated, but it will not show up if called before the form is shown on the screen.

To test this you can add a button and add the code to the click event:

private void button1_Click(object sender, EventArgs e)
{
    using (Graphics g = panel1.CreateGraphics())
    {
        g.DrawLine(new Pen(Color.Back, 3), new Point(234,118), new Point(293,228));
    }
}
Share:
23,962
Badmiral
Author by

Badmiral

Updated on July 09, 2022

Comments

  • Badmiral
    Badmiral almost 2 years

    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.

  • Simon Whitehead
    Simon Whitehead over 11 years
    Perhaps it would be best to lead by example and wrap that in a using statement? :)
  • Badmiral
    Badmiral over 11 years
    Tried changing the g definition, nothing happened
  • Mike Webb
    Mike Webb over 11 years
    Changed my answer. Not the issue I though it was.
  • Combine
    Combine almost 9 years
    Other way of seeing the line is to create a button and draw your line in the OnClick Method of the button like so: private void btnDraw_Click(object sender, EventArgs e) { Graphics dc = drawingArea.CreateGraphics(); Pen BlackPen = new Pen(Color.Black, 2); dc.DrawLine(BlackPen, 0, 0, 200, 200); BlackPen.Dispose(); dc.Dispose(); }