Search code examples
c#winformsdrawingpanel

How to make a horizontal bar in a panel control when drawing on it?


I have a panel and I need to draw a horizontal chart on it. But sometimes the chart can be too long for the panel, even the form has maximum size. So I want to make a horizontal bar on panel to enable the user to see the remaining part of the drawing that is out of the bounds.

Chart is something like this:

enter image description here

As you can see, the chart is out of the panel's bounds and form's too. I don't have any idea how can it be done, so I have no code to show. So how can I do it using a basic method?


Solution

  • Yes, the solution is pretty basic, as long as the size you want to draw won't go over 32k pixels width:

    • Put your Panel inside another one.
    • The outer Panel has AutoScroll=true
    • The inner one where you draw has the size of your drawing.
    • You need to draw in the Paint event, as you should anyway (!)

    Now the outer Panel shows a horizontal scrollbar and the user can scroll right and left and see all parts of the drawing..

    One alternative would be to add a dummy control that enforces the AutoScroll of your drawing Panel to work, but I find using two Panels the cleaner way to go..

    Note: You should either use a PictureBox or at least a double-buffered Panel subclass to avoid flicker and tearing:

    class DrawPanel : Panel
    {
        public DrawPanel()
        { DoubleBuffered = true; }
    }
    

    Update: Instead of a Panel, which is a Container control and not really meant to draw onto you can use a Picturebox or a Label (with Autosize=false); both have the DoubleBuffered property turned on out of the box and support drawing better than Panels do.