Reputation: 449
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;
Upvotes: 2
Views: 1414
Reputation: 103555
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);
};
Upvotes: 2