Hello,I have a function that draws a rectangle on a form (different widths and heights)

public void drawRectangle()
    Graphics g = pictureBox1.CreateGraphics();
    Rectangle rect = new Rectangle(50, 50, 60, 50);
    g.DrawRectangle(Pens.Black, 10, 10, 10, 10);

I have a picturebox called picturebox1 but how would I get the rectangle to display in the picture box?

Thanks =)

7 Years
Discussion Span
Last Post by ddanbe

Other than you create a rectangle object then don't use it to draw the rectangle, I don't see a problem with the code. Are you having some issue?


The rectangle you've asked it to create is very small, only 10 pixels on a side. Maybe you just don't notice it.

This very code draws a nice black rectangle on my computer.


Drop a PictureBox on your from and set up its Paint event handler like this

private void pictureBox1_Paint(object sender, PaintEventArgs e)
            Graphics g = e.Graphics;
            Pen bluePen = new Pen(Color.Blue, 2);
            g.DrawRectangle(bluePen, 10, 10, 50, 20);        }

It will draw a nice blue rectangle with a blue pen of two pixels wide.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.