2

i need to draw a line for example, in a dynamically created PictureBox. What happens is that the picture box is created and shown in the form but the line is missing. My code is below, any ideas?? thnx

public void create_pb()
{
    PictureBox pb = new PictureBox();
    pb.Size = new Size(200, 200);
    pb.BorderStyle = BorderStyle.Fixed3D;
    pb.Location = new Point(0,0);
    panel1.Controls.Add(pb);
    g = pb.CreateGraphics();
    Pen p = new Pen(Color.Black, 2);

    g.DrawLine(p, 0, 0, 200, 200);           
}

g is defined as public Graphics g;

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Stavros Afxentis
  • 289
  • 1
  • 4
  • 16
  • have you checked out the `Invalidate()` Method sounds like this could be the problem also here is an existing working project that can give you some ideas as well .[CodeProject Drawing on PictureBox](http://www.codeproject.com/Tips/318900/Drawing-on-picture-box-images) – MethodMan Feb 09 '15 at 21:41
  • Have a look at the bottom of [this answer](http://stackoverflow.com/questions/28403514/drawing-a-moving-line-in-a-transparent-panel-in-c-sharp/28405275#28405275), especially the setting up of the event handlers! – TaW Feb 09 '15 at 22:42

1 Answers1

2

Don't use CreateGraphics. You need to do your drawing in the Paint event handler instead, using e.Graphics from the event arguments passed to you.

Otherwise your line will simply be erased when the picture box is next repainted (e.g. when the form is moved, resized, covered by another form, etc).

Example:

pb.Paint += (sender, e) =>
{
    Pen p = new Pen(Color.Black, 2);
    e.Graphics.DrawLine(p, 0, 0, 200, 200);
};
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272