Search code examples
c#winformssystem.drawing

c# winforms - scrollable panel with rectangles


I'm new to winforms and have tried to track down an answer to the following with no luck ...

I have a panel in winforms and add to it a Rectangle that is wider than the panel itself. I've set the panel AutoScroll property to true however the panels horizontal scrollbar never appears. Why is this? And how do I get the scrollbar to scroll?

Here is my code to add the rectangle:

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;

        Rectangle rec = new Rectangle(2, 2, 400, 40);
        g.DrawRectangle(new Pen(Color.Black), rec);
        g.FillRectangle(new SolidBrush(Color.Blue), rec);
    }

If I add a Label control to the panel and give it a text value that will go beyond the bounds of the panel - then the autoscroll works, but just not for a rectangle.

Many thanks.


Solution

  • Set the AutoScrollMinSize property to the size of the larger rectangle:

    panel1.AutoScrollMinSize = new Size (400, 400)