Ravindu
Ravindu

Reputation: 2550

How can I draw a rectangle inside a panel in C#?

I want to draw a rectangle and I want to give position it with respect to the panel bottom.

    public void populateTable(int x, int y)
    {
        using (Graphics g = this.CreateGraphics())
        {
            Brush b = new SolidBrush(Color.Red);
            g.FillRectangle(b, x, y, 100, 40);
        }

    }

When I execute the code above, the rectangle is created successfully. But it's positioned with respect to form, not the panel. If I put x=10, y=10, then it's shown in the upper left corner of the form. But I want to show it in the bottom where I put a panel.

Upvotes: 0

Views: 4781

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103575

this.CreateGraphics() creates a Graphics object for this, which is the enclosing class - the form in this case.

You should try panel1.CreateGraphics() instead.

However, I would recommend not using CreateGraphics at all. It's better to handle OnPaint, so that your graphics gets redrawn when the form is redrawn (minimized then maximized, etc).

Upvotes: 2

Related Questions