How do I draw a circle and line in the picturebox?
The best way is to NOT draw a circle and line in a picturebox! It is not designed for that purpose.
From Bob Powell's GDI+ blog:
The root of this problem is that the fundamental rules of windows programming have been broken. And as a consequence of the picture box is blamed for something that's really not its fault. To help explain why, the four points below outline what's gone wrong in this case.
The PictureBox control is for displaying images. It is not a handy placeholder for a graphics surface.
Windows is an event driven system in which each event must be serviced in the correct context and events destined to handle button click or mouse move events must not be used to do drawing on screen or other weird stuff.
The PictureBox refreshes itself by drawing the System.Drawing.Image based object stored in it's Image property. If there is no image, it will show the background colour.
Stealing and drawing upon the Graphics object of any control is not good practice, should be strongly discouraged and breaks the rules of handling events in the right place at the right time. Basically if you do this it will cause you pain. When you bang your head against a wall it causes you pain. that is a sign that you should stop doing it. It's the same for the PictureBox.CreateGraphics call.
The right way to do it.
Following the rules of the event driven system is easy but requires a little forethought. So, if you want to draw some little bit of graphics and have it remain there when a window moves in front of it and away again or when you minimize and restore, you have to service the Paint event of whatever object it is that you wish to paint on. The PictureBox carries baggage around with it that is unnecessary for this kind of application. If you just want to draw something in one place, draw it on the form by responding to the Form.Paint event. If you want a handy placeholder for a graphic that works within a set bounds, use a Panel control and service it's Paint event. If you want to duplicate a graphic over and over for your corporate image, create a control and do the drawing in the OnPaint override.
Source: https://web.archive.org/web/20120330003635/http://bobpowell.net/picturebox.htm (the original site is defunct).
or:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(
new Pen(Color.Red,2f),
new Point(0,0),
new Point(pictureBox1.Size.Width, pictureBox1.Size.Height ));
e.Graphics.DrawEllipse(
new Pen(Color.Red, 2f),
0,0, pictureBox1.Size.Width, pictureBox1.Size.Height );
}
Handle the paint event of the picture box and do your custom drawing there.
the picturebox is a control and has an image as source - so you have to draw on the image and hand the image to the control to show it
MyImage = new Bitmap(fileToDisplay);
pictureBox1.ClientSize = new Size(xSize, ySize);
pictureBox1.Image = MyImage;